I’ve been hand crafting a lot of Mock objects recently to help ensure the tests that I’m writing are only testing a single object. Mock objects along with constructor dependency injection make it possible to test one and only one class which is a very important attribute of good unit tests.
To help reduce the number of hand crafted mocks I need to create I’ve been looking at some mock frameworks to help. Over the last week I’ve looked at Rhino Mocks and NMock but wasn’t able to get some simple examples working. This was mostly due to not having sufficient time to look into the API’s and read the supporting documentation. This afternoon I did a quick search for “.net mock framework” and came upon the NUnit release notes which reminded me that a simple Mock framework was included with NUnit 2.2. I added a reference to NUnit.Mocks and started experimenting. Within a couple minutes I had the basics I needed to start using the mock framework within NUnit. Although it isn’t meant to be a full fledged mock framework it provides the basic features necessary for most mocks.
using System;
using NUnit.Framework;
using NUnit.Mocks;
namespace NUnitMocks.Samples {
[TestFixture]
public class MockTests {
public interface IMyInterface {
string SayHello();
}
DynamicMock mock;
IMyInterface m;
[SetUp]
public void Setup() {
mock = new DynamicMock(typeof(IMyInterface));
m = (IMyInterface)mock.MockInstance;
}
[Test]
public void CanSetReturnValue() {
mock.SetReturnValue("SayHello", "Steve");
Assert.AreEqual("Steve", m.SayHello());
}
[Test]
public void CanSayWeExpectOrDoNotExpectSomethingToBeCalled() {
mock.ExpectNoCall("SayHello");
mock.Verify();
mock.Expect("SayHello");
m.SayHello();
mock.Verify();
}
[Test]
[ExpectedException(typeof(Exception))]
public void CanGetExceptionThrown() {
mock.ExpectAndThrow("SayHello", new Exception("We got issues"));
m.SayHello();
}
}
}