Moq and constructors - testing initialisation behaviour - c#

I'd like to be able to test a class initialises correctly using Moq:
class ClassToTest
{
public ClassToTest()
{
Method1(#"C:\myfile.dat")
}
public virtual void Method1(string filename)
{
// mock this method
File.Create(filename);
}
}
I thought I'd be able to use the CallBase property to create a testable version of the class, then use .Setup() to ensure Method1() does not execute any code.
However, creating the Mock<ClassToTest>() doesn't call the constructor, and if it did it'd be too late to do the Setup()!
If this is impossible, what is the best way round the problem whilst ensuring that the constructor behaves correctly?
EDIT: To make it clearer, I've added a parameter to Method1() to take a filename and added some behaviour. The test I'd like to write would be a working version of the following:
[Test]
public void ClassToTest_ShouldCreateFileOnInitialisation()
{
var mockClass = new Mock<ClassToTest>() { CallBase = true };
mockClass.Setup(x => x.Method1(It.IsAny<string>());
mockClass.Verify(x => x.Method1(#"C:\myfile.dat"));
}

Way down inside of Moq.Mock (actually inside the CastleProxyFactory that Moq uses)
mockClass.Object
will call the constructor by way of Activator.CreateInstance()
So your test would look something like
[Test]
public void ClassToTest_ShouldCreateFileOnInitialisation()
{
Mock<ClassToTest> mockClass = new Mock<ClassToTest>();
mockClass.Setup(x => x.Method1(It.IsAny<string>());
var o = mockClass.Object;
mockClass.Verify(x => x.Method1(#"C:\myfile.dat"));
}

Related

Mocking an Extention method C# [duplicate]

I have a preexisting Interface...
public interface ISomeInterface
{
void SomeMethod();
}
and I've extended this intreface using a mixin...
public static class SomeInterfaceExtensions
{
public static void AnotherMethod(this ISomeInterface someInterface)
{
// Implementation here
}
}
I have a class thats calling this which I want to test...
public class Caller
{
private readonly ISomeInterface someInterface;
public Caller(ISomeInterface someInterface)
{
this.someInterface = someInterface;
}
public void Main()
{
someInterface.AnotherMethod();
}
}
and a test where I'd like to mock the interface and verify the call to the extension method...
[Test]
public void Main_BasicCall_CallsAnotherMethod()
{
// Arrange
var someInterfaceMock = new Mock<ISomeInterface>();
someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable();
var caller = new Caller(someInterfaceMock.Object);
// Act
caller.Main();
// Assert
someInterfaceMock.Verify();
}
Running this test however generates an exception...
System.ArgumentException: Invalid setup on a non-member method:
x => x.AnotherMethod()
My question is, is there a nice way to mock out the mixin call?
I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.
See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.
You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach.
Here is the description of the tool:
Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.
Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.
You can use Moles with any testing framework (it's independent about that).
I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.
I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.
I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.
I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.
internal Func<IMyObject, string, object> DoWorkMethod
{
[ExcludeFromCodeCoverage]
get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
set { _DoWorkMethod = value; }
} private Func<IMyObject, string, object> _DoWorkMethod;
Then you call the Func instead of the actual method.
public object SomeFunction()
{
var val = "doesn't matter for this example";
return DoWorkMethod.Invoke(MyObjectProperty, val);
}
For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/
If you just want to make sure that the extension method was invoked, and you aren't trying to setup a return value, then you can check the Invocations property on the mocked object.
Like this:
var invocationsCount = mockedObject.Invocations.Count;
invocationsCount.Should().BeGreaterThan(0);
Reason why it is not possible to mock an extension method is already given in good answers. I am just trying to give another possible solution with this answer: Extract a protected, virtual method with the call to the extension method and create a setup for this method in the test class/method by using a proxy.
public class Foo
{
public void Method()
=> CallToStaticMethod();
protected virtual void CallToStaticMethod()
=> StaticClass.StaticMethod();
}
and test
[TestMethod]
public void MyTestMethod()
{
var expected = new Exception("container exception");
var proxy = new Mock<Foo>();
proxy.Protected().Setup("CallToStaticMethod").Throws(expected);
var actual = Assert.ThrowsException<Exception>(() => proxy.Object.Foo());
Assert.AreEqual(expected, actual);
}
In my case extension method is a method around some public method of my class. So I checked call of that internal method. That approach is similar to Alvis answer (above).
So if you are using Moq, and want to mock the result of an Extension method, then you can use SetupReturnsDefault<ReturnTypeOfExtensionMethod>(new ConcreteInstanceToReturn()) on the instance of the mock class that has the extension method you are trying to mock.
It is not perfect, but for unit testing purposes it works well.

Unit testing a method that uses an external dll

I have a project named A that has a class named ClassA.
ClassA has a method named ReadBlock() which creates a CloudBlockBlob object and calls one of its methods.
CloudBlockBlob is a class which is located in Microsoft.WindowsAzure.Storage.Blob namespace which is in Microsoft.WindowsAzure.Storage.dll.
My project A has a unit testing project named A.Tests.
Now, I want to test method ReadBlock(). To test it, I need to mock the CloudBlockBlob object and intercept the calls to its methods, return custom values and verify that the methods were called.
How can I mock an object that is fully created inside a method?
Can I somehow change project A's dll reference and reference it to a mock dll that creates a mock object instead the real one?
Can I override project A's call for classes inside the Microsoft.WindowsAzure.Storage.Blob with an implementation of my own in A.Tests class?
UPDATE:
The question is whether I can do this without modifying project A's code.
Thanks!
Without modifing class A code you won't be able to UT the ReadBlock method using Moq. You'll be able to UT this method using code weaving tools (MsFakes, Typemock Isolator, etc...)
For example(MsFakes):
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
ShimCloudBlockBlob.AllInstances.<the method you want to override> = (<the method arguments>) => {};
}
}
Inside the using scope you'll be able to override any method CloudBlockBlob has, through the property AllInstances.
In the next section I'm going to discuss all the other options you have...
Option 1:
public class A
{
private IBlockBlob _blockBlob;
public A(IBlockBlob blockBlob)
{
_blockBlob = blockBlob;
}
public void ReadBlock()
{
_blockBlob.DoSomething();
}
}
Since you create a new instance each time call ReadBlock(your method's current behavior) you better inject a factory instead of wrapper and DoSomething should be create; Option 2:
public class A
{
private readonly IFactoryBlockBlob _blobFctory;
public A(IFactoryBlockBlob blobFctory)
{
_blobFctory = blobFctory;
}
public void ReadBlock()
{
var blob = _blobFctory.Create();
}
}
However, based on your question and your comments it seems that your class 'has a dependency' instead of 'needs a dependency'.
(Mark Siemens wrote a great book about DI, this chart was taken from his book)
With this new piece of information your method should be something like; Option 3:
public class A
{
public void ReadBlock(ICloudBlob blob)
{
}
}
But you don't want to change the signature of the method:
public class A
{
public void ReadBlock()
{
ReadBlock(new CloudBlockBlob(<the params bla bla...>));
}
internal void ReadBlock(ICloudBlob blob)
{
}
}
Add InternalsVisibleToAttribute, then verify the behavior of the internal method.
By reading between the lines, it feels to me that your class is a kind of "legacy code" meaning that it can do the job, won't change, and verifying its behavior might be a waste of time. In the past I've posted a chart (in this answer) which may help you to decide the way to handle this case.
Its probably best to create a very simple mockable wrapper for CloudBlockBlob to improve your code's testability and inject it using dependency inversion.
Right now you probably have something like:
public class A
{
public void ReadBlock()
{
var blockBlob = new CloudBlockBlob();
blockBlob.DoSomething();
}
}
Instead, inject your wrapper into A so that the dependency on CloudBlockBlob is not known to A:
public class A
{
IBlockBlob _blockBlob
public A(IBlockBlob blockBlob)
{
_blockBlob = blockBlob;
}
public void ReadBlock()
{
_blockBlob.DoSomething();
}
}
Disclaimer, I work in Typemock.
You can do it without modifying project A's code using Isolator.
There is a simple example how it can be done:
public class Foo
{
public void ReadBlock()
{
var block = new CloudBlockBlob(new Uri("http://myUrl/%2E%2E/%2E%2E"));
var name = block.Name;
}
}
[TestMethod, Isolated]
public void TestReadBlock()
{
//Arrange
var fakeBlock = Isolate.Fake.AllInstances<CloudBlockBlob>();
Isolate.WhenCalled(() => fakeBlock.Name).WillReturn("Name");
//Act
var foo = new Foo();
foo.ReadBlock();
//Assert
Isolate.Verify.WasCalledWithAnyArguments(() => fakeBlock.Name);
}
Hope it helps!

Castle Class Proxy for unit tests

Scratching my head how to do this.
Suppose I had a concrete class Foo with 2 virtual methods, Execute() and GetFile(). Execute() will call GetFile. I want to make sure that when it does, GetFile() will throw a couple of different exceptions that Foo is supposed to handle gracefully in a testable manner.
For my unit tests, I am envisioning instantiating a DynamicProxy<Foo> from castle project where I intercept the GetFile() to throw the exception, and then invoke the DynamicProxy object's Execute() method, and test the results, but I can't see how to do this.
Is this possible/ practical? If so, what would the creation of the dynamic proxy object look like?
You don't need to handcode your own proxy because most the mocking frameworks support your scenario.
Here is an example using Moq (Moq will create a dynamic proxy internally for you):
public class SomeException : Exception { }
public class Foo
{
public virtual int Execute()
{
try
{
GetFiles();
}
catch (SomeException)
{
return 1;
}
return 0;
}
public virtual void GetFiles()
{
//...
}
}
[Test]
public void FooTest()
{
var fooUnderTest = new Mock<Foo>();
fooUnderTest.CallBase = true;
fooUnderTest.Setup(f => f.GetFiles()).Throws(new SomeException());
var result = fooUnderTest.Object.Execute();
Assert.AreEqual(1, result);
}
You just need to take care to set Callbase = true which will:
Invoke base class implementation if no expectation overrides the
member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false.

What is the proper way to use the Ninject RhinoMocksMockingKernel to test a class that has two constructor arguments of the same type?

I am testing a class that has two dependencies on IFoo. Both instances of IFoo should be MOCK objects so that I can VerifyExpectations on each. Each instance is created and managed by the RhinoMocksMockingKernel.
I think that the mocking kernel is getting confused about which instance it should be verifying.
I also think that I may be confused about the proper way to setup RhinoMocksMockingKernel for this case.
I do know that I can use dep1.AssertWasCalled... vs. dep1.VerifyAllExpectations().
Here is the sample code.
public interface IFoo
{
void DoX();
void DoY();
}
public class SubjectUnderTest
{
private readonly IFoo dep1;
private readonly IFoo dep2;
public void DoWork()
{
dep1.DoX();
dep2.DoY();
}
public SubjectUnderTest(IFoo dep1, IFoo dep2)
{
this.dep2 = dep2;
this.dep1 = dep1;
}
}
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = kernel.Get<IFoo>();
var dep2 = kernel.Get<IFoo>();
// tried this binding but it doesnt seem to work
kernel.Bind<SubjectUnderTest>()
.ToSelf()
.WithConstructorArgument("dep1", dep1)
.WithConstructorArgument("dep2", dep2);
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}
As ryber said, you should not really be using your IOC container in your tests that way. However, I'll still answer the question in case you have this issue in normal code. You can use the Named attribute as shown in this other stackoverflow question: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
In that example, the Named attribute is above of the function but you can also put it right next to your arguments to specify which one should be used. E.g.
public void SubjectUnderTest([Named("Alpha")] IFoo alpha, [Named("Beta")]) {
...
}
And the bindings should be registered as such described in this post: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
You can also use a the ToMethod binding to just manually create your object.
So I found a way to verify the expections on dep1 and dep2, but I was not able to use the AutoMockingKernel to manage and create dep1 and dep1.
Here is the code that I came up with.
It's pretty lame answer. It seems like I should be able to use the mocking kernel to Get two seperate instances of IFoo...
Here is my current code... lameo...
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = MockRepository.GenerateMock<IFoo>();
var dep2 = MockRepository.GenerateMock<IFoo>();
kernel.Bind<IFoo>().ToMethod((ctx) => dep1).When((ctx) => ctx.Target.Name.StartsWith("dep1"));
kernel.Bind<IFoo>().ToMethod((ctx) => dep2).When((ctx) => ctx.Target.Name.StartsWith("dep2"));
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}

Mocking Extension Methods with Moq

I have a preexisting Interface...
public interface ISomeInterface
{
void SomeMethod();
}
and I've extended this intreface using a mixin...
public static class SomeInterfaceExtensions
{
public static void AnotherMethod(this ISomeInterface someInterface)
{
// Implementation here
}
}
I have a class thats calling this which I want to test...
public class Caller
{
private readonly ISomeInterface someInterface;
public Caller(ISomeInterface someInterface)
{
this.someInterface = someInterface;
}
public void Main()
{
someInterface.AnotherMethod();
}
}
and a test where I'd like to mock the interface and verify the call to the extension method...
[Test]
public void Main_BasicCall_CallsAnotherMethod()
{
// Arrange
var someInterfaceMock = new Mock<ISomeInterface>();
someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable();
var caller = new Caller(someInterfaceMock.Object);
// Act
caller.Main();
// Assert
someInterfaceMock.Verify();
}
Running this test however generates an exception...
System.ArgumentException: Invalid setup on a non-member method:
x => x.AnotherMethod()
My question is, is there a nice way to mock out the mixin call?
I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.
See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.
You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach.
Here is the description of the tool:
Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.
Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.
You can use Moles with any testing framework (it's independent about that).
I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.
I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.
If you just want to make sure that the extension method was invoked, and you aren't trying to setup a return value, then you can check the Invocations property on the mocked object.
Like this:
var invocationsCount = mockedObject.Invocations.Count;
invocationsCount.Should().BeGreaterThan(0);
I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.
I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.
internal Func<IMyObject, string, object> DoWorkMethod
{
[ExcludeFromCodeCoverage]
get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
set { _DoWorkMethod = value; }
} private Func<IMyObject, string, object> _DoWorkMethod;
Then you call the Func instead of the actual method.
public object SomeFunction()
{
var val = "doesn't matter for this example";
return DoWorkMethod.Invoke(MyObjectProperty, val);
}
For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/
Reason why it is not possible to mock an extension method is already given in good answers. I am just trying to give another possible solution with this answer: Extract a protected, virtual method with the call to the extension method and create a setup for this method in the test class/method by using a proxy.
public class Foo
{
public void Method()
=> CallToStaticMethod();
protected virtual void CallToStaticMethod()
=> StaticClass.StaticMethod();
}
and test
[TestMethod]
public void MyTestMethod()
{
var expected = new Exception("container exception");
var proxy = new Mock<Foo>();
proxy.Protected().Setup("CallToStaticMethod").Throws(expected);
var actual = Assert.ThrowsException<Exception>(() => proxy.Object.Foo());
Assert.AreEqual(expected, actual);
}
In my case extension method is a method around some public method of my class. So I checked call of that internal method. That approach is similar to Alvis answer (above).
So if you are using Moq, and want to mock the result of an Extension method, then you can use SetupReturnsDefault<ReturnTypeOfExtensionMethod>(new ConcreteInstanceToReturn()) on the instance of the mock class that has the extension method you are trying to mock.
It is not perfect, but for unit testing purposes it works well.

Categories