当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《RhinoMocks:如何在方法调用中模拟方法调用?》经验,为你挑选了1个好方法。

我有一个非常简单的类,有两种方法; 一个将被调用,另一个将调用.想法是调用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();
     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();
     mockProvider.Expect(item => item.InnerMockMethod())
       .Return(new MockClass { SomeMessage = "Mocked" });
     repository.Replay(mockProvider);

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

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

tvanfosson.. 7

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

MockClass returnedMock = MockRepository.GenerateMock();
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).你可以在这里找到更多信息.



1> tvanfosson..:

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

MockClass returnedMock = MockRepository.GenerateMock();
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).你可以在这里找到更多信息.

推荐阅读
臭小子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有