My class has a method like this:
internal virtual Something CreateSomething(){...}
It was done this way so that in testing I can stub CreateSomething() to return a mock object:
var something = ...; //some mock object
var t = MockRepository.GenerateStub<MyObject>();
t.Stub(x => x.CreateSomething()).Return(something);
This worked fine but now CreateSomething() is called in the class constructor, before it was called later on, so by the time I stub the method my object is already created.
Is there a workaround that doesn't involve changing the design, to pass stub methods in at construction time? If not I can consider changing the design to use construction-injection (which I'm sure some of you are itching to suggest anyway!) but I'd rather see if Rhino supports this use-case first.
There is no way to stub the method before it is invoked from its class constructor. This is C# limitation. And this is reasonable.
In general it is a bad practice to call virtual method from the constructor, because likely the result will not be what is expected. See details here: Virtual member call in a constructor.
So, I highly recommend to either make this method non-virtual, or avoid its invocation from the constructor.
Anyway in such situation it won't work as virtual.
Regarding you question about testing the method, which is called from constructor.
I presume, this is a private method. Otherwise it could be tested as a regular public method.
As it is private, then there is no need to test this particular method in isolation. I recommend to follow general approach in testing constructors and testing private methods: Do not test private methods.
Test the public visible effect instead. That could be:
Public property initialization
Mocked dependencies invocation or properties access
Exception thrown
etc.
Please also find more details about this topic by the links below:
Is it important to unit test a constructor?
Unit testing private methods in C#
Related
I want to mock a class having no default constructor and call a method inside it. This method calls another method of the same class. I want to setup this second method to return a value ad execute rest of the part of first method to test some results.
[Test]
public void TestFunction(){
int d=0;
var mockObject = new Mock<Foo>(){MockBehaviour.Default, p, q}; //p and q are parameters for Foo constructor
mockObject.Setup(x=>x.func2(a,b,c)).Returns(d);
mockobject.Object.func1();
}
Class Foo{
public Foo(int x,int y){}
public virtual int func1(){
DoSomething;
func2();
}
public virtual int func2(){}
}
I am mocking Foo because I don't want func2() to be executed when I test func1(). Hence I setup the mockObject to return a value for func2() without executing it when func1() calls func2().
When I run this test case I get exception "System.NotSupportedException : Parent does not have a default constructor. The default constructor must be explicitly defined."
If I see the mockObject while debugging the test case, mockObject.Object is not getting initialized.
I am new to unit testing and Mock. Can someone help me about where I am going wrong.
The answer to your actual question:
How to Mock a class having no default construtor
You need to use a different overload of the Mock ctor so that arguments are passed to the non-default Foo ctor:
var mockObject = new Mock<Foo>(1, 2);
However your testing strategy is flawed and I believe this is due to how you understand Moq to function.
Mocks are useful for trivializing complex dependencies of what you are testing - instead of instantiating, handling their lifecycles, you mock them. This is okay when they don't affect the code you are actively testing (as others have mentioned in this question) -- that is not your intent here. Since Func2() is tightly coupled to the implementation of func1(), the way that the code is written now, there is not a way to execute Func1() without executing Func2().
You could change the function signature of Func1() to take Func2() as an argument -- this would allow you to modify which function is passed to it during testing (and allow you to Mock the behavior of Func2() easily. However you've already said this is an impossibility.
Too answer your question being posted you may simply provide the arguments, as suggested in this thread:
var mockObject = new Mock<Foo>(MockBehaviour.Default, FooParameters);
mockObject.Setup(x=>x.func2(a,b,c)).Returns(d);
mockobject.Object.func1();
However this isn´t a good idea though. Usually you shouldn´t mock your system under test. Doing so may indicate that your class is doing too much and needs to be restructured, in order to do exactly one single thing.
However there may be situations where a class has several API-members that depend on each other. Think of an overload-chain where you want to test multiple overloads. Of course it´s easy to write a test for the most inner overload (with most params). However if want to test if your other overloads set the params for the most inner one correctly, you´re indeed stuck.
void DoSomething()
{
var param = ...
DoSomething(param);
}
void DoSomething(int p)
{
// the most inner overload
}
There isn´t a general rule how to solve that dependency. I tend do subclass my system-under test in those cases and override its (virtual) members with an empty body - which is what MOQ internally does also.
Ok so i just got an assignment where i have to perform unit testing on a class with a private constructor.
Now how am i suppose to do unit testing without initializing a class when all the methods are also non static.
Is there any way i can do unit testing(without reflection)on a class with a private constructor ?
If you cannot make the class public, you can still test it easily by creating an instance of it this way:
var anInstance = (YourPrivateClass)Activator.CreateInstance(typeof(YourPrivateClass), true);
This will give you an instance of your class that you can then populate.
Another helpful testing bit is if you have internal methods (not private), you can access them by making internals visible to your test class. You add this line in assemblyinfo.cs of the class with the internal methods:
[assembly: InternalsVisibleTo("YourSolution.Tests")]
If this class has a private constructor, is this to be used publicly? If not, it may be best not to unit test it. If this is the case, the code that is public should test this code in itself by calling it.
Unit testing is there to test what is to be used by the public - by interfacing code in between application layers for instance. Take an input, I want this output. That is really what unit testing is about. Unit testing doesn't care what is in the actual method. As long as it returns what you want, performs the desired action, you have a pass.
You should be testing through a public API -- there must be some way that the class you want to test is instantiated and used.
Unit tests are typically written and run to ensure that code meets its design and behaves as intended.
Creating a non-static class on which you cannot create an instance i.e. private constructor(s) only, might never be useful, in otherwords its is never Unit Testable.
In order to be Unit testable:
You should be able to create an instance of the class.
Testable Function should be either Public or Internal.
You could test Internal function by making your assembly as a Friend Assembly
It might be a singleton and you don't want the public constructor for the class.
Decorate the constructor with:
[ExcludeFromCodeCoverage]
I have a function which calls many functions internally. I see in tutorials that test methods are designed in such a way that only the return values of outer functions are checked. How can I check the values returned by internal functions.
Only the GetValues() methods values are tested. How can i check the working of other methods inside GetValues(). How can I check its working using unit testing?
[TestFixture]
public class Class1
{
[Test]
public void Tester()
{
TesterClass clasObj;
int a = clasObj.GetValues();
Assert.AreEqual(10,a);
}
}
How can i check its working using unit testing?
In unit tests you only care about the, well, the unit, under test. In this case it is the GetValues. Also, usually only the public methods are unit tested. Because it is only the public methods ( interface) that has to be tested and not the internal workings.
It also ensures that the tests are not brittle. If you change the way a private / internal method works, but will essentially make the public interfaces work the same ( this especially when you are using mocks, and not really in the kind of testing you are doing), you shouldn't really be facing failed unit tests.
In such cases, you should be making sure that your unit tests cover all code path through the public method being tested and the private / internal methods that are being called by the method under test.
Sometimes, you do want to test the internals and one way is to use the InternalsVisibleToAttribute and mark the test assembly as a "friend".
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx
Another way is to subclass the class you are testing ( possibly in your test assembly), and add a public wrapper method to the method to be tested and use this proxy class and the public wrapper for testing.
I think you can do this with some tools, like TypeMock, but there is a reason why most tools don't allow it. This is because it usually makes the tests very brittle, meaning that when you change the internal code of a class, the tests will break. Internal members should be encapsulated and that is a good thing. I would look at a design that is testable from its public interface.
Generally you want to avoid testing the internal implementations of code, this is so that you can refactor and not break any tests. However, if you want to test the inside of another object, then the answer is easy. By wanting to test private implementation, the code smell is that the current object under test is doing too much work. In turn violating such rules as the single responsibility principle.
Therefore split out GetValues into a new object that you can test, such as:
ExampleFormatter.FormatValues()
Now this would be a public class with a public method meaning you can easily test it. All GetValues has to do now is invoke FormatValues with the correct params. You could use a mock object to verify that this happens as expected. As this is now public, when can test such things as the formatting of the values are as we expect and so forth. Any time you find it hard to test some code it usually means the code is doing too much, break it out!
How can I write a unit test for a method that has a using statement?
For example let assume that I have a method Foo.
public bool Foo()
{
using (IMyDisposableClass client = new MyDisposableClass())
{
return client.SomeOtherMethod();
}
}
How can I test something like the code above?
Sometimes I choose not to use using statement and Dispose() an object manually. I hope that someone will show me a trick I can use.
If you construct the IMyDisposableClass using a factory (injected into the parent class) rather than using the new keyword, you can mock the IMyDisposable and do a verify on the dispose method call.
public bool Foo()
{
using (IMyDisposableClass client = _myDisposableClassFactory.Create())
{
return client.SomeOtherMethod();
}
}
If you already have your code and are asking how to test it, then you're not writing your tests first...so aren't really doing TDD.
However, what you have here is a dependency. So the TDD approach would be to use Dependency Injection. This can be made easier using an IoC container like Unity.
When doing TDD "properly", your thought processes should run as follows in this sort of scenario:
I need to do a Foo
For this I will rely on an external dependency that will implement an interface (new or pre-existing) of IMyDisposableClass
Therefore I will inject an IMyDisposableClass into the class in which Foo is declared via its constructor
Then you would write one (or more) tests that fail, and only then would you be at the point where you were writing the Foo function body, and determine whether you needed to use a using block.
In reality you might well know that yes, you will use a using block. But part of the point of TDD is that you don't need to worry about that until you've proven (via tests) that you do need to use an object that requires this.
Once you've determined that you need to use a using block you would then want to write a test that fails - for example using something like Rhino Mocks to set an expectation that Dispose will get called on a mock object that implements IMyDisposableClass.
For example (using Rhino Mocks to mock IMyDisposableClass).
[TestFixture]
public class When_calling_Foo
{
[Test]
public void Should_call_Dispose()
{
IMyDisposableClass disposable = MockRepository
.GenerateMock<IMyDisposableClass>();
Stuff stuff = new Stuff(disposable);
stuff.Foo();
disposable.AssertWasCalled(x => x.Dispose());
}
}
Class in which your Foo function exists, with IMyDisposableClass injected as a dependency:
public class Stuff
{
private readonly IMyDisposableClass _client;
public Stuff(IMyDisposableClass client)
{
_client = client;
}
public bool Foo()
{
using (_client)
{
return _client.SomeOtherMethod();
}
}
}
And the interface IMyDisposableClass
public interface IMyDisposableClass : IDisposable
{
bool SomeOtherMethod();
}
Your question doesn't make sense. If you are using TDD, then you should already have a test for what you have written. Requirements, then tests, then design, then development. Either your code passes your tests, or it doesn't.
Now, if your question is how to unit test the above piece of code, then that's another question completely, and I think the other posters have answered it up there.
Sometimes I think there are more buzzwords than developers :)
Wrapper methods like that aren't unit-testable, because you can't specify the relevant preconditions or post-conditions.
To make the method testable, you'll have to pass an IMyDisposableClass instance into the method or into the class hosting Foo (and make the host class itself implement IDisposable), so you can use a test double instead of the real thing to verify any interactions with it.
Your question doesn't make sense. If you are doing TDD, then the method that you posted is already fully tested, otherwise it couldn't even exist in the first place. So, your question doesn't make sense.
If, on the other hand, the method that you posted does already exist, but isn't fully tested, then you aren't doing TDD anyway, and your question about TDD doesn't make sense, either.
In TDD, it is simply impossible for untested code to exist. Period.
You could also change the method signature to allow passing in a mock for unit testing. This would provide an alternative to using a factory, which would also need to be unit tested. DI into the method as opposed to the class constructor may be preferable here.
public bool Foo(IMyDisposableClass mock = null)
{
using (IMyDisposableClass client = mock ?? new MyDisposableClass())
{
return client.SomeOtherMethod();
}
}
If you are testing Foo, then you should be looking at the output of Foo, not worrying about the disposal of the class it is using internally.
If you want to test MyDisposableClass' dispose method to see if it is working, that should be a separate unit test built against MyDisposableClass.
You don't need to unit test the using { } block, since that is part of the language. You either trust that it's working, or don't use C#. :) I don't see the need to write a unit test to verify that Dispose() is being called.
Without a specification for Foo, how can we say how to test it?
Get the specification for Foo.
Write tests to ensure that it meets all specifications and requirements (or a reasonable subset- some functions could require practically infinite amounts of data to test).
I believe you have a second, implicit question in there - which is how to test that use of your MyDisposableClass correctly Disposes of the object when it is freed by exiting an using clause. This is a separate test issue, and shouldn't be combined with the test of Foo, since the specification of Foo shouldn't reference implementation specific details such as the use of your MyDisposabeClass.
I think the other posters have answered this question, so I won't further elaborate.
I have the following code (which I've dumbed down for the question):
public void HandleModeInit(int appMode){
switch(appMode){
Case 1:
DoThis();
Case 2:
DoThat();
Case 3:
//no mode 3
Case 4:
DoSomethingElse();
Case else:
//do nothing
}
}
How would you unit test this method without turning it into an integration test (where you end up testing what DoThis(), DoThat(), and DoSomethingElse() are doing)? Since these method calls are made to methods within the same class as HandleModeInit(), how would you test this?
Although ideally, the method calls would be extracted out into another class, what if this move doesn't make any sense?
If you have control over what is passed into this method then I would pass in an interface that takes appmode as an argument which is an AppModeImplementationFactory. The purpose of this factory is to create AppModeImplementations. The factory would look as follows:
public class AppModeImplementationFactory: IAppModeFactory
{
public IAppModeImplementation Create(int appMode)
{
// switch case goes here to create the appropriate instance
}
}
When you pass in the factory this can be a mocked instance and you can verify that the create method is called. If you want to verify the instance type that is returned you would need to do that under a different test. This approach will fulfill your need of executing logic because of the app mode because the factory will return the implementation that you need based on the appMode.
Hope this helps
Instead of using a switch/case statement to switch appModes, you can create an interface called IAppMode (I'll assume that the caller could decide which object to instanciate that properly implements IAppMode since they're already passing in an int to represent the App Mode).
Your caller would pass in an IAppMode object, then your method could call the DoThis() method of IAppMode.
You could then create a dummy object that implements IAppMode and inject it in to the method during testing.
It makes your code easer (using design patterns can do that) and test-able.
I realize (especially with you noting it) that the code is dumbed down, but if you do not test what the called methods do in this case, what are you actually testing? The value of appMode?
How exactly to attack this is hard (if not impossible) to say without knowing some about what is happening inside the called methods. Are they making any outbound calls (to external services, database, whatever) that can be mocked? If so, that may be a path forward. If they contain only behaviour that is encapsulated in the class, perhaps they alter some property value that you can check when the call to HandleModeInit returns?
I am typically not a fan of altering the design of my code for the sole purpose of making it more testable, but one approach would be to separate the public interface of your class from the internals, and then defining the internal interface as, well, an interface. That way you open up for mocking the internals.