我使用NMock进行了以下测试,但失败了。它曾经在服务调用的结果传递给视图时工作,但它现在失败,因为结果被转换为dto。
我认为这可能意味着我需要创建一个自定义匹配器,但我不确定。有没有人有任何想法?
错误讯息:
Test method Dgc.Cpo.RM.UI.Presentation.Test.ProjectPresenterTest.LoadProjectsTest threw exception: NMock2.Internal.ExpectationException: unexpected invocation of projectView.SetProjects(<System.Collections.Generic.List`1[Dgc.Cpo.ResourceManagement.UI.Presentation.ProjectPresentationDto]>)
预期: 1次:projectView.SetProjects(等于)[调用0次]
代码:
public void LoadProjectsTest()
{
IList<ProjectServiceGetProjectsResponse> expectedGetProjectsResponse = new List<ProjectServiceGetProjectsResponse>();
expectedGetProjectsResponse.Add(new ProjectServiceGetProjectsResponse() { Id = 1, Name = "Project 1", RefNo = "001", Complete = false, Dropped = false });
expectedGetProjectsResponse.Add(new ProjectServiceGetProjectsResponse() { Id = 2, Name = "Project 2", RefNo = "002", Complete = true, Dropped = false });
expectedGetProjectsResponse.Add(new ProjectServiceGetProjectsResponse() { Id = 3, Name = "Project 3", RefNo = "003", Complete = false, Dropped = true });
IList<ProjectPresentationDto> expectedSetProjectsRequest = new List<ProjectPresentationDto>();
expectedSetProjectsRequest.Add(new ProjectPresentationDto(expectedGetProjectsResponse[0]));
expectedSetProjectsRequest.Add(new ProjectPresentationDto(expectedGetProjectsResponse[1]));
expectedSetProjectsRequest.Add(new ProjectPresentationDto(expectedGetProjectsResponse[2]));
ProjectPresenter_Accessor target = new ProjectPresenter_Accessor(this.mockView,
this.mockProjectService);
Expect.Once.On(this.mockProjectService).Method("GetProjects").Will(Return.Value(expectedGetProjectsResponse));
Expect.Once.On(this.mockView).Method("SetProjects").With(expectedSetProjectsRequest);
target.LoadProjects();
this.mock.VerifyAllExpectationsHaveBeenMet();
}
答案 0 :(得分:2)
您已经拥有它 - 您需要创建自定义匹配器和静态工厂类,如NMock 2.0 advanced topics documentation中“NMock 2.0中的客户匹配器”部分所述。
默认情况下,NMock使用Equals
来匹配传递给期望的参数(在您的情况下,查看LoadProjects
是否将mockView.Projects
设置为expectedSetProjectsRequest
)。
List<T>.Equals
实施(继承自Object
)只是checks whether the two variables reference the same object,在这种情况下,他们显然没有。 (看起来LoadProjects
方法在将get访问器结果转换为DTO的过程中创建新的DTO列表实例。)
你必须告诉NMock该做什么而不是检查引用相等性。幸运的是,我上面链接的NMock文档中的自定义ListMatcher
(以及相应的IsList
类)可以单独完成所有操作。如果ProjectPresentationDto.Equals
检查值相等,则可以按原样使用该示例类。如果没有,您将必须对其进行自定义以定义DTO的相等性。