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.
Related
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#
I know I can't use Moq to mock out a static method call inside my method under test, so what would I need to do to refactor the method so I can test it? I also have a method calling the base class method, would I need to refactor that and if so how? I don't want to use MS.Fakes or TypeMocks and create a shim, I would rather refactor and write solid code!
public override DateTime ResolveDate(ISeries comparisonSeries, DateTime targetDate)
{
if (comparisonSeries == null)
{
throw new ArgumentNullException("comparisonSeries");
}
switch (comparisonSeries.Key)
{
case SeriesKey.R1:
case SeriesKey.R2:
case SeriesKey.R3:
case SeriesKey.R4:
case SeriesKey.R5:
return DateHelper.PreviousOrCurrentQuarterEnd(targetDate);
}
return base.ResolveDate(comparisonSeries, targetDate);
}
[TestMethod]
public void SomeTestMethod()
{
var mockIAppCache = new Mock<IAppCache>();
var mockISeries = new Mock<ISeries>();
ReportFR2 report = new ReportFR2(SeriesKey.FR2, mockIAppCache);
DateTime resolvedDate = report.ResolveDate(mockISeries, DateTime.Now);
//Assert.AreEqual("something", "something");
}
Looking at the above, you have three basic conditions you can test:
When Comparison Series is null
When the Comparison series key is R1:R5
When the Comparison series key is not null and anything but R1 : R5
In condition 1, you can cover this with a test pretty easily.
In condition 2, When it's R1:R5, that is where it appears it hits your static method.
From the perspective of your ResolveDate method, you still care what the value is when it hits this branch.
It would be nice to be able to prove that R1:R5 call the static helper, but as mentioned in the comments, the only way to cleanly do that is to wrap your DateHelper with an interface and pass that to the constructor of this class. That may not be worth the effort.
If you decide not to do that, I suggest that you still give a test that falls into that branch, and then also write another set of tests that targets your DateHelper.PreviousOrCurrentQuarterEnd() function directly, hitting all the edge cases. This will help isolate which code is the culprit if something fails.
The same can be said for condition 3 as condition 2. Although it's in your base class, it's still a valid logic branch.
Again, you will have a hard time proving that it called your base class,
But it is still valid to check the outcome.
So, I think you have four sets of tests you can write to start out, and then after you have these passing, you can decide if you want to take on refactoring your utility class DateHelper. My guess is you'll say no :-D
Given a ReportRF2 class and a null Comparison series
When calling report.ResolveDate
It should throw a Null reference exception. Use
`Assert.Throws( () => report.ResolveDate( null, DateTime.Now ));
Given a ReportRF2 class and a series key in the set of R1:R5
When Resolving the Date for boundary X (such as 1/1/0001), it should equal y;
When ".." for ..., ...; (repeat for your edge/boundary cases; consider using Data Driven)
Given the ReportRF2 class and a series key NOT in the set of R1:R5 and NOT NULL
when Resolving the Date for boundary X, ... similar to #2 but probably different expected results.
Given the static utility class DateHelper
when calculating the PreviousOrCurrentQuarterEnd() and the date is X, it should equal y,
similar to edge cases in #2 above.
That will then give you coverage of the expected results, and tells you failures are stemming from your ResolveDate method or your DateHelper.PreviousOrCurrentQuarterEnd() method. It may not isolate as much as a purist would like, but as long as you cover your edge cases and your happy paths, it proves your app is functioning as planned (as long as those tests are passing).
What it does not really let you do is assert that a specific behavior is taken, other than when the comparison series is null, so it's up to you to decide if you need that verification. But, you should still have proof that when certain values or ranges go in, you get predictable outputs, and that adds some value.
Just to add to #Damon's nice answer, wrapping the DateHelper with an interface can be done quite easily:
public interface IDateHelper
{
DateTime PreviousOrCurrentQuarterEnd(DateTime targetDate);
}
As noted, you'll need an instance class that implements this interface, but only for your production code, since unit tests will just use a Mock<IDateHelper:
public class InstanceDateHelper : IDateHelper
{
public DateTime PreviousOrCurrentQuarterEnd(DateTime targetDate)
{
return DateTimeHelper.PreviousOrCurrentQuarterEnd(targetDate);
}
}
Voilà, you can now mock the IDateHelper interface and you have an implementation that uses the existing static code.
I've used this wrapping technique for writing unit tests on a method that launches a new Process, so I could test the method without actually launching a full-fledged process when all I needed to know was whether the method under test would call .Start(StartInfo), without the side-effects.
Picture this method:
public bool StartProcessAndWaitForExit(ProcessStartInfo info)
{
var process = Process.Start(info); // test-hindering static method call
//...
}
The only change I had to make was this:
public bool StartProcessAndWaitForExit(IProcessWrapper process, ProcessStartInfo info)
{
var process = process.Start(info); // injected wrapper interface makes method testable
//...
}
If ResolveDate is the only method in your class that requires an IDateHelper, injecting it as a method parameter is fine; if you have a bunch of methods that would all need it as well, injecting it as a constructor argument and making a private readonly IDateHelper _helper; field (initialized in the constructor) is the best way to go.
I have a class as follows.
public class MyClass
{
public MyMethod()
{
int x = CalculateSomething();
}
private int CalculateSomething()
{
// Do something and return an int
return 100;
}
}
To unit test this I added [assembly: InternalsVisibleTo("MyTests")] and changed the private method to be internal virtual.
In the unit test project I created a class MockMyClass and created private method as follows.
public class MockMyClass : MyClass
{
public bool MadeHappyNoise {get; set;}
internal override int CalculateSomething()
{
MadeHappyNoise = true;
return base.CalculateSomething();
}
}
The unit test is now as follows
[TestMethod()]
public void WasCalculateSomethingCalledOK()
{
MockMyClass mk = new MockMyClass();
mk.MyMethod();
Assert.IsTrue(mk.MadeHappyNoise, "Oops...CalculateSomething not called...");
}
Few questions: Is this is a good way to remove dependencies? I personally don't like to change a method from private to internal but have no option (other than to use Reflection perhaps). Also, the attribute InternalsVisibleTo("MyTests") residing in the production code is not good. Can someone point me to a better solution please? Thanks.
It rather depends on the methods you are changing the scope of. A unit is the smallest testable component of a piece of software - it rarely means one test per method.
I find that comprehensively testing my public methods is enough to establish correct behaviour. You might find that your tests start to constrain your code development if you wrap the private methods with tests.
If your program is more procedural you might find that you need to test at the granular level you describe, in which case using friend assemblies is a fine solution. However, I'd suggest that you would rarely need to test methods that aren't public.
Too much work for too little value. All that test tells me (if it passes) is that calling MyMethod calls another private method. The unit test should be testing the behavior provided by MyMethod() - what should happen/change after a call to MyMethod?.
The title of the question is a bit misleading too - there is no dependency-related issue that I can see.
You do not need InternalsVisibleTo for the most part.. simply test the private method through the public method that exercises it e.g. Write unit tests for MyMethod(). Also if you practice test-first programming, you'd already have tests that cover every line of code in the private method.
Hmm. I have some issues with that code, but we'll do one at a time.
Why would you want to test if MyMethod calls CalculateSomething? It's an implementation detail that is probably likely to change (what if it calls CalculateSomething2 tomorrow but apart from that still does what it's supposed to do?). If you want to test the code structure of MyMethod, do a code review, not a unit test.
You say that MyMethod is complex and you want to test the code flow inside. If there are multiple paths inside, you still have to write a unit test for each path, so why can't you check the result of calling MyMethod instead of checking the inside of it?
Another thought would be to try and refactor MyMethod into methods that lend themselves to easier testing (that's almost automatic if you do test-driven-development, a practice I recommend if you want to do serious unit testing. The "test later" approach almost always leads to code that is much more difficult to test).
If you still want to check the inner workings of MyMethod, maybe you can refactor the private methods you need to check this into another class (say "Calculations" in your example).
Then you can use a mock framework (like RhinoMocks for example), to mock that class. The framework lets you define what functions you expect to be called in what order and what they should return.
Usually you use mocks to lessen the environment requirements for unit tests, but you can use them in this way also.
Can you maybe refactor it to be like this:
public class MyClass
{
private Calculator calculator;
public myMethod()
{
int x = calculateSomething();
}
public void SetCalculator( Calculator c ){
calculator = c;
}
private int calculateSomething()
{
return calculator.CalculateSomething();
}
}
And then have calculator as a separate class and set an instance on MyClass
public Class Calculator {
public virtual int CalculateSomething()
{
// Do something and return an int
return 100;
}
}
You could make Calculator implement an interface and then have a different Calculator implementation or a mock that you use in your tests.
If this is a piece of legacy code that you are too scared to touch, i would advise you to create a unit test which would construct MyClass. Tentatively create a public property in MyClass to expose the value of x.
In the unit test just created assert that value of x is 100 after MyClass is instantiated. Once you have that in place, refactor like #alb suggests. Run the test again, make sure x is still 100 and test the calculator class separately and eventually remove the tentative public property for x in MyClass. hope that helps.
Using Moq, I have a very odd issue where the setup on a mock only seems to work if the method I am setting up is public. I don't know if this is a Moq bug or if I just have this wrong (newbie to Moq). Here is the test case:
public class TestClass
{
public string Say()
{
return Hello();
}
internal virtual string Hello()
{
return "";
}
}
[TestMethod]
public void Say_WhenPublic_CallsHello()
{
Mock<TestClass> mock = new Mock<TestClass>();
mock.Setup(x => x.Hello()).Returns("Hello World");
string result = mock.Object.Say();
mock.Verify(x => x.Hello(), Times.Exactly(1));
Assert.AreEqual("Hello World", result);
}
Which fails with this message:
Say_WhenPublic_CallsHello failed: Moq.MockException:
Invocation was not performed on the mock 1 times: x => x.Hello()
at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times)...
If I make the Hello method public like this, the test passes. What is the issue here?
public virtual string Hello()
{
return "";
}
Thanks in advance!
The test fails when Hello() is internal because Moq cannot provide an override of the method in this case. This means that the internal implementation of Hello() will run, rather than mock's version, causing the Verify() to fail.
Incidentally, what you are doing here makes no sense in the context of a unit test. A unit test should not care that Say() calls an internal Hello() method. This is implementation internal to your assembly and not a concern of consuming code.
I don't know enough about how this works underneath the covers to give you a technical answer as to exactly why that is the behaviour, but I think I can help with your confusion.
In your example you are calling a method Say(), and it is returning the expected text. Your expectation should not enforce a particular implementation of Say() ie that it calls an internal method called Hello() to return that string. This is why it does not pass the verify, and also why the string returned is "", ie the actual implementation of Hello() has been called.
By making the Hello method public it appears that this has enabled Moq to intercept the call to it, and use it's implementation instead. Therefore, in this case the test appears to pass. However, in this scenario you haven't really achieved anything useful, because your test says that when you call Say() the result is "Hello World" when in acutal fact the result is "".
I have rewritten your example to show how I would expect Moq to be used (not necessarily definitive, but hopefully clear.
public interface IHelloProvider
{
string Hello();
}
public class TestClass
{
private readonly IHelloProvider _provider;
public TestClass(IHelloProvider provider)
{
_provider = provider;
}
public string Say()
{
return _provider.Hello();
}
}
[TestMethod]
public void WhenSayCallsHelloProviderAndReturnsResult()
{
//Given
Mock<IHelloProvider> mock = new Mock<IHelloProvider>();
TestClass concrete = new TestClass(mock.Object);
//Expect
mock.Setup(x => x.Hello()).Returns("Hello World");
//When
string result = concrete.Say();
//Then
mock.Verify(x => x.Hello(), Times.Exactly(1));
Assert.AreEqual("Hello World", result);
}
In my example, I have introduced an interface to an IHelloProvider. You will notice that there is no implementation of IHelloProvider. This is at the heart of what we are trying to achieve by using a mocking solution.
We are trying to test a class (TestClass), which is dependant on something external (IHelloProvider). If you are using Test Driven Development then you probably haven't written an IHelloProvider yet, but you are aware that you will need one at some point. You want to get TestClass working first though, rather than get distracted. Or perhaps IHelloProvider uses a database, or a flat file, or is difficult to configure.
Even if you have a fully working IHelloProvider, you are still only trying to test the behaviour of TestClass, so using a concrete HelloProvider is likely to make your test more prone to failure, for instance if there is a change to the behaviour of HelloProvider, you don't want to have to change the tests of every class that uses it, you just want to change the HelloProvider tests.
Getting back to the code, we now have a class TestClass, which is dependant on an interface IHelloProvider, the implementation of which is provided at construction time (this is dependency injection).
The behaviour of Say() is that it calls the method Hello() on the IHelloProvider.
If you look back at the test, we have created an actual TestClass object, since we actually want to test the code that we have written. We have created a Mock IHelloProvider, and said that we expect it to have it's Hello() method called, and when it does to return the string "Hello World".
We then call Say(), and verify the results as before.
The important thing to realise is that we are not interested in the behaviour of the IHelloProvider, and so we can mock it to make testing easier. We are interested in the behaviour of TestClass, so we have created an actual TestClass not a Mock, so that we can test it's actual behaviour.
I hope this has helped to clarify what is going on.
Moq doesn't do partial mocking and can only mock public virtual methods or interfaces. When you create a Mock you are creating a completely new T and removing all implementation of any public virtual methods.
My suggestion would be to concentrate on testing the public surface area of your objects and not their internals. Your internals will get coverage. Just make sure you have a clear idea of what your target class is and don't mock that (in most cases).
Partial mocking is only useful when you want to test the functionality of an abstract class with mocked implementations of abstract methods. If you aren't doing this, you are likely not going to see much benefit from doing a partial mock.
If this is not an abstract class, you will want to focus more on the approach Modan suggests, which is to say that you should mock dependencies rather than your target class itself. All of this boils down to the rule don't mock what you are testing.
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.