我有一个mvc 3项目,我想模拟HttpResonseBase和HttpRequestBase。我使用RhinoMocks 3.6来模拟myobjects。我的测试代码就像这样。
[TestMethod]
public void Test()
{
MockRepository repo = new MockRepositoy();
HttpContextBase mockHttpContext= repo.StrictMock<HttpContextBase>();
HttpRequestBase mockRequest = repo.StrictMock<HttpRequestBase>();
HttpResponseBase mockResponse = repo.StrictMock<HttpResponseBase>();
ICookie mockCookie = repo.StrictMock<ICookie>();
Controller instanceToTest = new Controller(mockCookie);
SetupResult.For(mockHttpContext.Request).Return(mockRequest);
SetupResult.For(mockHttpContext.Response).Return(mockResponse);
mocks.Replay(context);
instanceToTest.ControllerContext = new ControllerContext(mockHttpContext, new RouteData(), instanceToTest);
mockCookie.Expect(x=>x.MethodToExpect("Test",mockRequest,mockResponse);
mockRepository.ReplayAll();
instanceToTest.MethodToTest();
mockRepository.VerifyAll();
}
当我运行测试时,我得到了这个错误消息;
Rhino.Mocks.Exceptions.ExpectationViolationException: ICookie.MethodToExpect("Test", System.Web.HttpResponseBase, System.Web.HttpRequestBase); Expected #0, Actual #1.
ICookie.MethodToExpect("Test", HttpResponseBaseProxy); Expected #1, Actual #0.
我做错了什么?
答案 0 :(得分:5)
这里的问题是你使用StrictMock
- 这意味着如果你在Mock对象上调用一个你没有设置任何期望的方法,VerifyAllExpectations
将会失败。您可以使用MockRepository.GenerateMock<T>
方法代替StrictMock
。
另一个评论是你最好坚持RhinoMocks AAA syntax(使用Expect
,Stub
和VerifyAllExpectations
方法而不是ReplayAll
,SetupResult
等...)
以下是使用纯AAA语法编写代码的方式:
[TestMethod]
public void Test()
{
// Arrange(A) - create your objects, mocks and stubs
// The context is a Stub - you just want it to return the mocked request and response
HttpContextBase mockHttpContext= MockRepository.GenerateStub<HttpContextBase>();
HttpRequestBase mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
HttpResponseBase mockResponse = MockRepository.GenerateMock<HttpResponseBase>();
ICookie mockCookie = MockRepository.GenerateMock<ICookie>();
Controller instanceToTest = new Controller(mockCookie);
// Stub will return the mocked request and response on every call (similar to SetupResult)
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
mockHttpContext.Stub(x => x.Response).Return(mockResponse);
instanceToTest.ControllerContext = new ControllerContext(mockHttpContext, new RouteData(), instanceToTest);
mockCookie.Expect(x=>x.MethodToExpect("Test",mockRequest,mockResponse);
// Act(A) - do the actual operations on the tested class
instanceToTest.MethodToTest();
// Assert (A) - Verify your expectations
mockCookie.VerifyAllExpectations();
}