views:

25

answers:

2

How do I check if Create was not called without using the Rhino Mocks AssertWasNotCalled method.

Here is the test:

    [Test]
    public void When_try_to_create_directory_that_already_exits_return_false()
    {
        var directoryInfoMock = MockRepository.GenerateMock<IDirectoryInfoWrap>();
        directoryInfoMock.Stub(x => x.Exists).Return(true);
        directoryInfoMock.Expect(x => x.Create());
        Assert.AreEqual(false, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoMock));

        directoryInfoMock.VerifyAllExpectations();
    }

Also, can someone clarify what Stub does.

+2  A: 
directoryInfoMock.Stub(x => x.Exists).Return(true);

ensures that any call to the property directoryInfoMock.Exists will return true. But if the property is never call or called many times, it will not cause the test to fail. The purpose of the stub is to provide some meal to your code under test so that it can run normally.

directoryInfoMock.Expect(x => x.Create());

expects that the method directoryInfoMock.Create be called at least once. If not, an exception will be thrown by Rhino.Mocks during the execution of directoryInfoMock.VerifyAllExpectations().

So basically, your unit test should work as expected. What is the output of the test?


UPDATE:
You might want to specify an explicit number of times the method should be called as well. This can be done by using Repeat.x with x is Once(), Twice(), Never(), or Times(N).

directoryInfoMock.Expect(x => x.Create()).Repeat.Never();

This expects that Create is never called. And of course your test will fail if it is actually called.

Yann Trevin
Well I have one test where I want Create to be called and that works, but I have another test where I don't want Create to be called and was curious if there was something like a DoNotExpect this method to be called. Also regarding your answer on stubs, if I understand you correctly, I am basically setting the Exists property to true on the Directory object instead of having to explicitly set it somewhere else. If there were other properties I needed to set, I could stub them as well, correct?
Xaisoft
For the "DoNotExpect" pattern, you may use the `Repeat` property of Rhino.Mocks. See my updated answer.
Yann Trevin
+1  A: 

If you need to make sure that only the methods you expect are called you can consider using strict mocks. Then you will get an exception when a method was called that was not expected on your mock, the only change to your code is when you create your mock:

var directoryInfoMock = MockRepository.GenerateStrictMock<IDirectoryInfoWrap>();

if you know exactly which method shouldn't be called its better to use AssertWasNotCalled (you use it after your test was executed). This way you don't tie your test with your code so closely.

Grzenio