How to Mock a Static Singleton? - c#

I have number of classes I've been asked to add some unit tests to with Rhino Mocks and having some issues.
First off, I know RhinoMocks doesn't allow for the mocking of Static members. I'm looking for what options I have (besides using TypeMock).
An example of the class I have is similar to the below:
class Example1 : ISomeInterface
{
private static ISomeInterface _instance;
private Example1()
{
// set properties via private static methods
}
static Example1()
{
_instance = new Example1();
}
public static ISomeInterface Instance()
{
get { return _instance; }
}
// Instance properties
// Other Instance Properties that represent objects that follow a similar pattern.
}
So when I call the above class, it looks something like this...
Example1.Instance.SomeObject.GoDownARabbitHole();
Is there a way for me to mock out the SomeObject.GoDownARabbitHole() in this situation or mock out the Instance?

Discouraged by threads like this, it took me quite some time to notice, that singletons are not that hard to mock. After all why are we using c#?
Just use Reflection.
With provided sample code you need to make sure the static constructor is called before setting the static field to the mocked object. Otherwise it might overwrite your mocked object. Just call anything on the singleton that has no effect before setting up the test.
ISomeInterface unused = Singleton.Instance();
System.Reflection.FieldInfo instance = typeof(Example1).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Mock<ISomeInterface> mockSingleton = new Mock<ISomeInterface>();
instance.SetValue(null, mockSingleton.Object);
I provided code for mocking with Moq, but I guess Rhino Mocks is quite similar.

Singletons are at odds with Testability because they are so hard to change. You would be much better off using Dependency Injection to inject an ISomeInterface instance into your consuming classes:
public class MyClass
{
private readonly ISomeInterface dependency;
public MyClass(ISomeInterface dependency)
{
if(dependency == null)
{
throw new ArgumentNullException("dependency");
}
this.dependency = dependency;
}
// use this.dependency in other members
}
Notice how the Guard Claus together with the readonly keyword guarantees that the ISomeInterface instance will always be available.
This will allow you to use Rhino Mocks or another dynamic mock library to inject Test Doubles of ISomeInterface into the consuming classes.

Here's a low-touch approach that uses a delegate, which can be set initially and changed at runtime. It's better explained by example (specifically, mocking DateTime.Now):
http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/11/09/systemtime-versus-isystemclock-dependencies-revisited.aspx

Example from Book: Working Effectively with Legacy Code
To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it
setTestingInstance.
public class PermitRepository
{
private static PermitRepository instance = null;
private PermitRepository() {}
public static void setTestingInstance(PermitRepository newInstance)
{
instance = newInstance;
}
public static PermitRepository getInstance()
{
if (instance == null)
{
instance = new PermitRepository();
}
return instance;
}
public Permit findAssociatedPermit(PermitNotice notice)
{
...
}
...
}
Now that we have that setter, we can create a testing instance of a
PermitRepository and set it. We’d like to write code like this in our test setup:
public void setUp() {
PermitRepository repository = new PermitRepository();
...
// add permits to the repository here
...
PermitRepository.setTestingInstance(repository);
}

Check out Dependency Injection.
You've already began this, but for hard to test classes (statics etc...) you can use the adapter design pattern to write a wrapper around this hard to test code. Using the interface of this adapter, you can then test your code in isolation.
For any unit testing advice, and further testing issues check out the Google Testing Blog, specifically Misko's articles.
Instance
You say you are writing tests, so it may be too late, but could you refactor the static to the instance? Or is there a genuine reason why said class should remain a static?

You can mock the interface, ISomeInterface. Then, refactor the code that uses it to use dependency injection to get the reference to the singleton object. I have come across this problem many times in our code and I like this solution the best.
for example:
public class UseTheSingleton
{
private ISomeInterface myX;
public UseTheSingleton(ISomeInterface x)
{
myX = x;
}
public void SomeMethod()
{
myX.
}
}
Then ...
UseTheSingleton useIt = UseTheSingleton(Example1.Instance);

You don't have to fix all the uses at once, just the one you're dealing with now. Add an ISomeInterface field to the class under test and set it through the constructor. If you're using Resharper (you are using Resharper, aren't you?), most of this will be trivial to do. If this is really fiddly, you can have more than one constructor, one which sets the new dependency field, the other which calls the first one with the singleton as a default value.

Related

Using the Singleton pattern with an interface in C#

Note: Even though there are a lot of similar questions, non that i have found answered my question.
Problem:
I would like to implement a class in C# which uses the singleton pattern in the following way.
namespace DAL
{
public class CDAL : IDAL
{
/* Singleton Pattern */
private CDAL instance = null;
private CDAL()
{
}
public IDAL getInstance()
{
if (instance != null)
{
return instance;
}
else
{
CDAL.instance = new CDAL();
return CDAL.instance;
}
}
}
}
the problem is that instance and the method getInstance should be static, as i want to 'ask' the class for that instance and not an object.
but using c# i can't seem to do anything static in an interface.
how can i solve this?
You're right, you cannot do anything static on an interface, since it does not make any sense.
Use an abstract class instead of the interface to implement static logic.
It does not make any sense creating an interface with a static member.
Interfaces are a contract while the static member is always accessed by the class name, not the instance name. so briefly your interface does not know which the correct instance implementing the right logic.
in your case you don't need your method getInstance() to be defined in the interface.
Interface when used with Singleton is often just for unit testing purposes

Ways to setup a Ninject singleton

I have a class (MyFacade) that I injected parameter(s) with Ninject:
class MyFacade
{
IDemoInterface demo;
public MyFacade(IDemoInterface demo)
{
this.demo = demo;
}
public void MyMethod()
{
Console.WriteLine(demo.GetInfo());
}
}
Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter (IDemoInterface)
I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes)
if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
The second one look a better approach, but do you know any other way to setup it in a singleton way?
When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you.
In your second example binding, what you are missing is binding in your IDemoInterface. Your bindings should look like this:
//bind the dependency to the implementation.
kernel.Bind<IDemoInterface>().To<DemoInterface>();
//since you bound your dependency, ninject should now have
// all the dependencies required to instantiate your `MyFacade` object.
kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
If you do not want the container to manage the lifecycle of your singleton by using InSingletonScope(), but still wants it to get injected, I can think of 2 ways to go about it. Choose which one suits better to your needs. Consider the following ISingleton (name your interface) implementation:
public class ConcreteSingleton : ISingleton
{
private static readonly Lazy<ConcreteSingleton> _instance = new Lazy<ConcreteSingleton>(() => new ConcreteSingleton());
private ConcreteSingleton() { }
public static ConcreteSingleton Instance
{
get
{
return _instance.Value;
}
}
}
Alter the singleton class to have a GetInstance(...) method
In this method (my preferred approach), you won't be calling kernel.Inject(instance) each time, only for the first time the singleton is initialized. Adding the following method to your ConcreteSingleton class:
public static ConcreteSingleton GetInstance(IKernel kernelForInjection)
{
if (_instance.IsValueCreated == false)
{
kernelForInjection.Inject(_instance.Value);
}
return _instance.Value;
}
And using this binding:
kernel.Bind<ISingleton>().ToMethod(c => ConcreteSingleton.GetInstance(c.Kernel));
Will achieve the desired behavior of not having a public constructor but enabling your facade to be efficiently injected.
Perform injection each time the ISingleton instance is requested
If by any reason you are not allowed to modify your ConcreteSingleton: This approach will wrap the singleton creation in a provider to efficiently inject the instance only for the first time it is created. It is important to note that the provider itself must be registered as a singleton.
internal class ConcreteSingletonProvider : Provider<ISingleton>
{
public IKernel Kernel { get; set; }
//Just a wrapper
private readonly Lazy<ISingleton> _lazy = new Lazy<ISingleton>(() => ConcreteSingleton.Instance);
public ConcreteSingletonProvider(IKernel kernel)
{
Kernel = kernel;
}
protected override ISingleton CreateInstance(IContext context)
{
if (_lazy.IsValueCreated == false)
{
Kernel.Inject(ConcreteSingleton.Instance);
}
return _lazy.Value;
}
}
And your bindings should be like this:
kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>();
kernel.Bind<ConcreteSingletonProvider>().ToSelf().InSingletonScope();
This gist has a complete working sample for the above approach.
Hope that helps!

Rhino mock unit testing (Parent class does not contain a constructor that takes 0 arguments)

Rhino Mock Experts please help.
Below Example of rhino mock is working fine.
internal class TestClass
{
private ITestInterface testInterface;
public TestClass(ITestInterface testInterface)
{
this.testInterface = testInterface;
}
public bool Method1(int x)
{
testInterface.Method1(x);
return true;
}
}
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();
TestClass tc = new TestClass(mockProxy);
bool result = tc.Method1(5);
Assert.IsTrue(result);
mockProxy.AssertWasCalled(x => x.Method1(5));
}
}
Problem i am facing as per above code is i need to create a constructor in all child classes like this:-.
internal class testclass1 : TestClass
{
protected testclass1(ITestInterface testInterface) : base(testInterface)
{
}
}
Is there any workaround for it as i am having around 50 child classes?
As mentioned in my comment to your question, this isn't really an issue caused by mocking or unit testing. It is a natural consequence of using constructor injection (ie. providing Dependencies as constructor arguments). An alternative is to use property injection, that is, creating a writable property by which you can set your ITestInterface object, like so:
public class TestClass {
public ITestInterface FooBar {protected get; set; }
}
This way, all derived classes have access to FooBar without the need to create their own constructor that passes the ITestInterface through to the base class.
However, this has other consequences: constructor injection typically expresses mandatory dependencies. Without that dependency, the class won't work. Property injection, however, is often used to express optional dependencies or a way to override the default behavior. This distinction isn't set in stone, though, and if your really have dozens of classes deriving from TestClass constructor injection can become a real burden to maintain.
If an object requires constructor arguments it is very obvious to the user that he must pass the required dependencies. With property injection it is much easier to forget to set the property to properly set up the object (if the dependency is required). Also, with constructor injection you only need to check if the dependency has been provided once (in the constructor), while with property injection it's more likely that you need to check the validity of the dependency each time you use it.
Again, if using constructor injection results in a maintenance nightmare because you have many sub classes, property injection is still a viable option despite what I wrote before.
You could additionally express the required property dependencies by using an initialization method like:
public static class TestClassInitializer{
public T Initialize<T>(this T t, ITestInterface dependency) where T:TestClass{
t.FooBar = dependency;
return t;
}
}
If you can force yourself to construct objects like this:
var tc = new DerivedTestClass().Initialize(mockTestInterface);
You have a single point where you can modify required dependencies. If you now need a second dependency, just update the signature to include the second dependency
public static class TestClassInitializer{
public T Initialize<T>(this T t, ITestInterface dependency, IOtherDependency other) where T:TestClass{
t.FooBar = dependency;
t.OtherDependency = other;
return t;
}
}
And all places where you call Initialize will break at compile time. This is a good thing(!) because you need to provide the required dependencies. However, you only need to update those places, not the 50 derived classes to add an additional dependency. If you had used constructor injection you what have needed to update all 50 classes and all places where you instantiate them.
Also: if you know that your derived classes only have a default constructor, you can create a factory method for all classes :
public static class TestClassFactory{
public static T Create<T>(ITestInterface dep1, ITestInterface dep2) where T :TestClass, new(){
return new T{FooBar = dep1, OtherDependency = dep2};
}
}
Instead of new DerivedTestClass().Initialize(...) you can now use TestClassFactory.Create<DerivedTestClass>(mockedDep1, mockedDep2);. You can make the actual constructors (protected) internal if you want as long as the TestClassFactory is in the same assembly (or in an assembly that can access the internal constructors through InternalsVisibleTo).
All this is less of an issue if you use a dependency injection framework/IoC container, as it won't forget to provide the dependencies once setup correctly.

Require Factory class in Extension Method

I am working on a large legacy C# application and a task assigned to me is to remove all usages of a static factory class ServiceLocator.GetObject<T>() and replace with constructor injected dependencies throughout.
For the most part, this is simple, however there are around 50 cases in the application codebase where this is a bit tricky. For instance, Servicelocator is used in a static class, or extension method, or even a WPF MarkupExtension!.
For instance, if you were faced with a code snippet like this, what would you do? (apart from cry)
public static class MyExtensions
{
private static ISingletonServiceOne _ServiceOne = null;
private static ISingletonServiceTwo _ServiceTwo = null; // etc ...
public static SummaryHeader GetBannerSummary(this IModel rfq, object requester)
{
Guard.ArgumentNotNull(rfq, "rfq");
Guard.ArgumentNotNull(requester, "requester");
if (_ServiceOne == null)
{
_ServiceOne = ServiceLocator.GetService<ISingletonServiceOne>(requester);
Guard.ArgumentNotNull(_ServiceOne, "_ServiceOne");
}
return _ServiceOne.GetBannerSummary(rfq);
}
In the above the ServiceLocator.GetObject() method has been used in an Extension Method on IModel to locate a singleton registered service and execute a method on that using IModel.
The question is:
Are there any patterns/practices to avoid this sort of thing - a DI container needed in a static class, value-converter or extension method
Are there any patterns/practices to deal with cyclic dependencies in DI?
What would you do in the above given there is a trade off between good code and time to delivery?
I am thinking to move the GetBannerSummary() method out of extensions and only IModel in this case, however (don't laugh) there are also cases of the same ServiceLocator being used in ValueConverters (WPF) and MarkupExtensions :0
Your comments/suggestions appreciated
The only time I would ever use ServiceLocator is in static methods, e.g. extension methods, and IValueConverters as, unfortunately, there really isn't any other good way of getting dependencies.
The only (slightly) better solution is to move the ServiceLocator call out to a lazy loaded property, so that the dependency can be injected during unit testing.
In your case, however, that won't fly as you have a requester property being passed to the GetService, in which case you ideally need to add an IServiceOneFactory dependency to which you can pass your requester object. So:
public interface IServiceOneFactory
{
ISingletonServiceOne Create(object requester);
}
public static class MyExtensions
{
public static IServiceOneFactory ServiceOneFactory
{
get
{
if( _ServiceOneFactory==null)
_ServiceOneFactory = ServiceLocator.GetService<IServiceOneFactory>();
return _ServiceOneFactory;
}
set { _ServiceOneFactory = value; }
}
private static IServiceOneFactory _ServiceOneFactory = null;
private static ISingletonServiceOne _ServiceOne = null;
private static ISingletonServiceTwo _ServiceTwo = null; // etc ...
public static SummaryHeader GetBannerSummary(this IModel rfq, object requester)
{
Guard.ArgumentNotNull(rfq, "rfq");
Guard.ArgumentNotNull(requester, "requester");
if (_ServiceOne == null)
{
_ServiceOne = ServiceOneFactory.Create(requester);
Guard.ArgumentNotNull(_ServiceOne, "_ServiceOne");
}
return _ServiceOne.GetBannerSummary(rfq);
}
}
Is it an option to inject IServiceX into your classes instead of using the a static accessor class? Perhaps make GetBannerSummary method part of an abstract base class that implements IModel?
DI does not fly when you don't control object instantiation. Triggers, Behaviors or Markup-Extensions in WPF fall into that category. There is no option to using a ServiceLocator there.

How to setup private constructor?

How do I setup the unit test if the constructor is private (.NET)?
This is my class:
public class Class2
{
// Private constructor.
private Class2()
{
}
public static Class2 getInstance()
{
if (x == null)
{
x= new Class2();
}
return x;
}
}
This is my unit test:
[TestFixture]
public class Class2Tester
{
private Class2 test;
[SetUp()]
public void SetUp()
{
// I cant do this. How should I setup this up?
test = new Class2();
}
}
The answer is: you don't. Not because you can't, but because you shouldn't.
By making the constructor private, you're saying that its behavior is not part of the public API of the class. In this case its behavior either a) doesn't affect the public API of the class which means it doesn't need to be tested. b) more likely, does affect the public API of the class, in which case, write your tests around that public API, not the black-boxed constructor.
You don't specify a language so my answer will be generic. The typical way to do this is using reflection. You can do it directly in each test or by creating an accessor class that wraps all of the private methods/properties, including the constructor.
An example from C#/.NET
public void MyTest()
{
MyClass class = typeof(MyClass).GetConstructor( null )
.Invoke( null );
...
}
Or, more typically, after adding private accessors to your test project
public void MyTest()
{
MyClass class = ((MyClass)new MyClass_Accessor()).Target;
}
In java (and this assumes the only constructor is the private default constructor, otherwise checking of the array is required):
Constructor[] constructors = YourClass.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
YourClass currentInstance = (YourClass) constructors[0].newInstance(null);
Then, currentInstance is available for you to use.
Typically I'll only do this for code coverage, if I make a constructor private, it's generally to avoid instantiation.
Depends on what you are doing in the private constructor.
If you are using a private constructor to disallow creating of an instance of a utility class then I suggest that you throw an illegalaccesserror similar to what you see in EJ2.
In that case you can simply test it via reflections that it won't be bypassed.
#Test(expected = InvocationTargetException.class)
public void privateConstructor() throws Exception {
final Constructor<Keys> myConstructor = Keys.class.getDeclaredConstructor();
myConstructor.setAccessible(true);
myConstructor.newInstance();
}
I don't disagree with this type of testing. It can help find places that are accidentally creating an instance of your util class where you didn't mean for it to (serialization/deserialization etc).
It could mean for some nasty surprises too if they were (highly not recommended) stateful.
I usually don't unit test constructors at all. In this situation, the first thing you should ask yourself is if you really do need to unit test the code in this constructor. Of course the paranoid perfectionist in all of us will come out at times, so if the answer is no, I say just forget about it.
If the answer is yes, I'm of the opinion that there's a good chance that you're doing too much with your constructor and/or your class. Even if this isn't the case, there's a good chance that you can break the code that does need to be unit tested into its own public function.
Granted, there are always exceptions. But I've yet to run into an instance where I had to make a constructor private and I had to unit test it.
Basically, you should not do that. See this question.

Categories

Resources