Nice trick for mock objects
I'm currently using mocks to create the Controller, before writing any GUI code whatsoever, which means that I've an interface for View, and I'm using mocks throughout the tests. The library that I'm using is NMock*, which allows to setup Expectations such as expecting calls on a spesific method.
The really nice thing about NMock is that it let you knows if you called a method too many times (just had it in one of my tests, and there was no way that I would have found out about this if I didn't have tests and if I didn't use NMock. However, if you want to know if a method was not called, you need to call the Verify() method. This is a ripe ground for forgetting to do so and creating bad tests, so now I've the following system:
[TestFixture]
public class ControllerTests
{
private Controller controller;
private Mock mockMgr;
[SetUp]
public void SetUp()
{
mockMgr = new DynamicMock(typeof(IViewManager));
controller = new Controller(TestDataUtil.CreateTestManager(),
(IViewManager)mockMgr.MockInstance);
}
[TearDown]
public void TearDown()
{
mockMgr.Verify();
}
[Test]
public void DisplayProject()
{
mockMgr.ExpectAndReturn("CloseProject",true);
mockMgr.Expect("DisplayProject",new IsTypeOf(typeof(Project)));
controller.DisplayNewProject();
}
}
- In SetUp() method - Create the mock objects
- In each test, set up expectation for this spesific test
- In TearDown() method - Verify() that the expectation were met.
This makes sure that I won't forget to call Verify() and miss a failed expectation.
* This is one of those rare projects where all the documentation you need is on the front page, and using the library is super easy. One of those things that you just never thinks about. Very happy with it.
Comments
Comment preview