tags:

views:

22

answers:

1

I have a question about Rhino Mock.

I am trying to put restriction on what methods could be called from the method that is under test.

Lets say I have a method that I am writing the Unit Test against like this:

public void MyMethod()
{
   var test = _Repository.Get(2);

   _Services.DoSomething(test);
}

what I do right now is something like this :

[Test]
public void TestMethod()
{
   var mock1 = CreateMock<IRepository>();
   var mock2 = CreateMock<IServices)();

    mock1.Expect(x => x.Get(1).IgnoreArguments().Return(new Poo()).Repeat.Once();
    mock2.Expect(x => x.DoSomething(new Something()).IgnoreArguments().Repeat.Once();

    ClassUnderTest.MyMethod();

    mock1.VerifyAllExpectations();
    mock2.VerityAllExpectations();
}

this is fine but what I want is to prevent somebody to change the method like this:

public void MyMethod()
{
   var test = _Repository.Get(2);

   var test = _Repository.Save(test);

   _Services.DoSomething(test);
}

As you can see Save method on Repository is called, so this is dangerous obviously because if somebody by mistake add that line there we will be in trouble.

How can I restrict someond from doing that ? Thanks.

+2  A: 

There are a few options:

Strict Mocks

Strict mocks throw an exception if they are called in a way that doesn't match an expectation. You can create strict mocks like this:

var mocks = new MockRepository();
var fooStrictMock = mocks.StrictMock<IFoo>();

.Repeat.Never()

If you are only interested in preventing calls to just one particular method, you can use the .Repeat.Never() quantifier on an expectation like this:

mock1.Expect(x => x.Save(null)).IgnoreArguments().Repeat.Never();

AssertWasNotCalled

You can call AssertWasNotCalled at the end of your test like this:

var repositoryStub = MockRepository.GenerateStub<IRepository>();
repositoryStub.Stub(x => x.Get(2)).Return(...);

var underTest = new UnderTest(repositoryStub);
underTest.DoSomething();

repositoryStub.AssertWasNotCalled(x => x.Save(Arg<Thing>.Is.Anything));
Wim Coenen
Thanks for your answer. There is a small problem. using the Repeat.Never() and AssertWasNotCalled is a bit slow, because lets say if I have 20 methods that I don't want to be then I have to list all of them like above.the first option looks good but I couldn't quite get it to work using AutoMock. I will try again later.
Raha