Rhino Mocks:如何在方法调用中模拟方法调用?

时间:2008-12-15 23:04:08

标签: rhino-mocks

我有一个非常简单的类,有两种方法;一个将被调用,另一个将调用。想法是调用OuterMockMethod方法但是模拟InnerMockMethod。现在我似乎只能模拟OuterMockMethod方法。

public class MockClass : IMockInterface
{         
    public virtual MockClass InnerMockMethod()
    {
      MockClass returnValue;

      returnValue = new MockClass();
      returnValue.SomeMessage = "Not mocked";

      return returnValue;
    }

    public virtual MockClass OuterMockMethod()
    {
      MockClass mock;

      mock = new MockClass();

      return mock.MockedMethod();
    }
}

现在这样可行,但这不是我想要模拟的方法:

 public void MockTest_Internal()
 {
     MockClass returnedClass;
     MockClass mockProvider;

     mockProvider = repository.StrictMock<MockClass>();
     mockProvider.Expect(item => item.OuterMockMethod())
       .Return(new MockClass { SomeMessage = "Mocked" });
     repository.Replay(mockProvider);

     returnedClass = mockProvider.OuterMockMethod();

     Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
 }

正如你所看到的,它调用它喜欢的OuterMockMethod,但我不想这样。我想模拟InnerMockMethod,这样当它被OuterMockMethod调用时,它将返回我想要的内容。

 public void MockTest_Internal()
 {
     MockClass returnedClass;
     MockClass mockProvider;

     mockProvider = repository.StrictMock<MockClass>();
     mockProvider.Expect(item => item.InnerMockMethod())
       .Return(new MockClass { SomeMessage = "Mocked" });
     repository.Replay(mockProvider);

     returnedClass = mockProvider.OuterMockMethod();  //Boom angry Rhino

     Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
 }

1 个答案:

答案 0 :(得分:7)

在这种情况下,您需要将模拟放在返回的对象上:

MockClass returnedMock = MockRepository.GenerateMock<MockClass>();
returnedMock.Expect( rm => rm.InnerMockMethod() )
            .Return( new MockClass { SomeMessage = "Mocked" } );
mockProvider.Expect( mp => mp.OuterMockMethod() ).Return (returnedMock );

returnedClass = mockProvider.OuterMockMethod();

...

请注意,StrictMock已被弃用。首选模式现在是AAA(Arrange,Act,Assert)。您可以找到更多信息here