stubbing protected abstract method using Rhino Mocks - rhino

I have a protected abstract method. Is there anyway I can stub it? Basically the template method calls that abstract method and I need it to stub it. The method cannot be amedted to public since it will break the encapsulation. Is there anyway I can achieve it using Rhino Mocks. I'm using 3.5 verion.
Thanks.

If it is possible you could make the method internal and expose internals to the test assembly (assuming your tests are not in the same assembly as the abstract class). It would change your encapsulation model, but the method would not be overidable outside the assembly, so as assembly owner you have control over this.

Related

How to use DI inside a static Method in Asp.net Core rc1

I see defaut template use ServiceProvder.GetService<ApplicationDbCotnext>() to initialize a DbContext,
But when you inside a Static Method, I have no idea how to get a DbContext, because there is no ServiceProvider.
Is there a way to get the ServiceProvider ?
Well, first of all, this has nothing to do with asp.net-core per se. This has more to do with how Dependency Injection works. You have to ask yourself why your method is static. Is that really necessary?
If you can't get rid of your static method, you might as well go all the way and introduce another anti-pattern, the Service Locator Pattern. In short: In the Startup class you put a reference to the ServiceProvider in a static property (call it for instance "ServiceProviderSingleton") of a static class (for instance "ServiceProviderProvider"). This way you can just call "ServiceProviderProvider.ServiceProviderSingleton.GetService()".
Again, i suggest giving your overal design a critical look. But if this is what you need/want then I hope it helped.
If we have a look at Microsoft's static methods (extension) - they seem not to use logging there - just throw appropriate Exception, for example in UseMvc method (for StartUp class):
https://github.com/aspnet/Mvc/blob/760c8f38678118734399c58c2dac981ea6e47046/src/Microsoft.AspNetCore.Mvc.Core/Builder/MvcApplicationBuilderExtensions.cs

How do I perform constructor injection with an NServiceBus saga?

If I have a class HelperClass that I'd like to use within a saga, I'd like to be able to inject an IHelperClass into the constructor.
The problem I'm running into is that sagas appear to be instantiated with an empty constructor; so while I can create a constructor that takes IHelperClass and use it in unit tests, the framework will always call the parameterless constructor.
I think I could use property injection, but since this helper class is "necessary," my understanding is that property injection (assuming it would work) is not a best practice.
So how can I do this without taking a hard dependency on the concrete HelperClass implementation?
You don't have to worry about the "necessity" of the help object in the context of the saga since no other code will be instantiating the saga directly.
In short, you can use property injection without concern here.

Force .NET MVC Controller to Call Service Methods Rather Than Directly Calling Base Class

I have a standard class stack in a .NET MVC5 using Entity Framework 6:
MyController()
MyService() : ServiceBase()
ServiceBase() : IServiceBase
All methods/classes are public at the moment.
ServiceBase() contains generic(T) methods and is inherited by all services.
The problem is that MyController() can call the generic methods in ServiceBase() directly. Important properties need to be set on the Entity before being passed to ServiceBase().
Is there any way to hide the ServiceBase() methods from MyController() forcing MyController() to go through MyService() rather than calling ServiceBase() methods directly?
Thanks all.
Why are you starting from an interface? I think you are getting your OO a little confused. I think the problem you are having is that you start at an interface, which doesn't have method visiblity controls. So you try to hide it in ServiceBase, but MyService has to know about the interface so that is why you cannot change visibility midway through.
I would suggest you rethink your OO strategy a bit.
However, if you really want to keep the interface and hide the methods in the base class, you can blank them out in MyService and inside of another method of MyService you can directly call the base class. I have created an example here.
But like I said, I would discourage this behavior and come up with a better OO strategy. If you can get around to posting your code, perhaps in a separate question, then I and the rest of the community can help you out with that. FYI, this might go better in the codereview stackexchange site.
The answer is to make the base classes that I don't want the controllers to access directly abstract while continuing to contain method implementation.
Make the ServiceBase classes abstract with a protected constructor. Then only classes that derive from them can access their methods directly, forcing the controller to call the controllers service which then calls the base service classes.
I wrote all this up in a blog post here

Generic method interception in grails (specifically Controllers)

I'm trying to create a generic function in grails that will allow me to specify a class and function name, and intercept any function calls based on that criteria:
getSomeClass().metaClass.invokeMethod = { String methodName, args ->
MetaMethod someAction = getSomeClass().metaClass.getMetaMethod(methodName, args)
def result = someAction.invoke(delegate, args)
if (methodName==getSomeMethodName())
intercept(args, result)
return result
}
This works for POGO, and domain classes, but does not seem to work for controller classes. While I'm fully aware there are Controller interceptors and filters available in Grails, these don't really centralise what I'm trying to achieve, and was trying to create a simple generic function for some centralised behaviour
Any guidance on why this doesn't work on Controllers would be appreciated, thanks
Your approach will work for method calls that are made through the Groovy metaclass mechanism, but in Grails 2 this doesn't apply to controller actions - they're called using normal Java reflection (java.lang.reflect.Method.invoke), and therefore your custom invokeMethod is bypassed.
If you want an AOP mechanism that'll work for calls from Java as well as from Groovy you'll probably have to use something like AspectJ load-time weaving. Spring's proxy-based AOP may work but the Grails 2 controller system relies on the action methods having a particular #Action annotation (which is added at compile time by an AST transformation) and I don't know whether Spring AOP proxies preserve method annotations from the target class on the generated proxy methods.
Could it be that MyController.metaClass.invokeMethod is overwritten by the grails framework after your definition?
Have you tried to check the content of MyController.metaClass.invokeMethod through reflection?

Practical Singleton & Dependency Injection question

Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.
Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:
PermissionManager.getInstance().isReadPermissionEnabled(this)
But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?
Additional info Note that when I say "Dependency Injection", I'm talking about the DI Pattern...I am not using any DI framework like Guice or Spring. (...yet)
If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you.
If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.
You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).
One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:
PermissionManager mManager = null;
public PermissionManager Permissions
{
if (mManager == null)
{
return mManager;
}
return PermissionManager.getInstance();
}
Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and that's what your other class should reference so a dummy implementation can be substituted more easily during testing.
You can indeed start by injecting the PermissionManager. This will make your class more testable.
If this causes problems for the users of that class you can have them use a factory method or an abstract factory. Or you can add a parameterless constructor that for them to call that injects the PermissionManager while your tests use another constructor that you can use to mock the PermissionManager.
Decoupling your classes more makes your classes more flexible but it can also make them harder to use. It depends on the situation what you'll need. If you only have one PermissionManager and have no problem testing the classes that use it then there's no reason to use DI. If you want people to be able to add their own PermissionManager implementation then DI is the way to go.
If you are subscribing to the dependency injection way of doing things, whatever classes need your PermissionManager should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.
Either way, though, the classic "capital-S" Singleton is generally seen as an anti-pattern in the context of dependency injection.
These posts have been insightful for me in the past:
Using Dependency Injection to Avoid Singletons
How to Think About the "new" Operator with Respect to Unit Testing
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.
The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.
In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.

Resources