views:

82

answers:

2

I have just crafted the following test using Rhino mocks. Does my test look valid and make sense to those more experienced with mocking?

I am a a little confused that I haven't had to use the DynamicMock() or StrictMock() methods to create a seemingly valid test.

This test tests that the Add method was invoked on the supplied ICachingStrategy with the supplied parameters.

    object o = new object();
    DateTime d = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 0, 0, 0);
    CacheStorageStyle s = CacheStorageStyle.Unmodified;
    string f = "test";

    //arrange  
    var stubStrategy = MockRepository.GenerateStub<ICachingStrategy>();
    var stubEncoder = MockRepository.GenerateStub<ICacheItemEncoder>();
    stubStrategy.Stub(x => x.Add(o,d,s,f)).Return("test:key");            
    stubEncoder.Stub(x => x.Encode(o,s)).Return(o);

    _mocks.ReplayAll();

    //act
    ICache c = new Cache(stubStrategy, stubEncoder);
    c.Add(o, d, s, f);

    //assert
    stubStrategy.AssertWasCalled(x => x.Add(o,d,s,f));
+4  A: 

The question is: does it succeed? Do you expect it to? If the answers are yes and yes, then the test is good. You can further test the test by forcing it to fail by commening out the call to Add() in your implementation. If the Add() method is not called, the test should fail.

Here is the relevant documentation that explains the difference between stubs and mocks. The essential difference is that stubs "will never cause a test to fail." They are there just to make the testing code work. The documentation further recommends that stubs should be preferred over mocks wherever possible.

Your test appears valid to me because you are primarily interested in whether the Add() method was called, and you are explicitly asserting for that call. You're not testing the other method calls, so you're stubbing them instead of mocking them.

Dave Swersky
+1  A: 

re: Strict vs Dynamic - another things thats worth noting is that in RhinoMocks 3.5 a call to MockRepository.GenerateMock() will not generate a strict mock.

Depending on what your testing you may/may not care what was/wasn't called on your mock.

Ralph Willgoss