我有一个非常简单的类,有两种方法; 一个将被调用,另一个将调用.想法是调用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).你可以在这里找到更多信息.
在这种情况下,您需要将模拟放在返回的对象上:
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).你可以在这里找到更多信息.