我投入了大量时间并且已经看到了不同的答案,但不知道什么是错的,无论我做什么,我总是得到返回值null。
我希望Return值是一个对象(模拟对象等),我可以在其上执行Assert操作。如果我在理解这个概念的错误轨道上请告诉我。
[Fact]
public void ProjectTest()
{
var ProjectServiceMock = new Mock<IProjectService>();
var ProjectMock = new Mock<IProject>();
IProject project = ProjectMock.Object;
ProjectServiceMock.Setup(x => x.CreateProject(new Path("C:"), "S1")).Returns(project);
var addProjectViewModel = new AddProjectViewModel(ProjectServiceMock.Object);
IProjectService obj = ProjectServiceMock.Object;
var result = obj.CreateProject(new Path("C:"), "S1");
}
result
始终为null
。
答案 0 :(得分:1)
您正在设置和模拟调用之间传递两个单独的实例,因此默认情况下它将返回null
。
您要么使用相同的实例
[Fact]
public void ProjectTest() {
var ProjectServiceMock = new Mock<IProjectService>();
var ProjectMock = new Mock<IProject>();
IProject project = ProjectMock.Object;
var path = new Path("C:");
ProjectServiceMock.Setup(x => x.CreateProject(path, "S1")).Returns(project);
var addProjectViewModel = new AddProjectViewModel(ProjectServiceMock.Object);
IProjectService obj = ProjectServiceMock.Object;
var result = obj.CreateProject(path, "S1");
}
或者使用它的参数匹配器与实际的参数实例
无关[Fact]
public void ProjectTest() {
var ProjectServiceMock = new Mock<IProjectService>();
var ProjectMock = new Mock<IProject>();
IProject project = ProjectMock.Object;
ProjectServiceMock.Setup(x => x.CreateProject(It.IsAny<Path>(), "S1")).Returns(project);
var addProjectViewModel = new AddProjectViewModel(ProjectServiceMock.Object);
IProjectService obj = ProjectServiceMock.Object;
var result = obj.CreateProject(new Path("C:"), "S1");
}
完成后,观察到基本上是在尝试测试模拟框架。在提供的示例中没有测试实际代码。
尝试按照测试的AAA方法
[Fact]
public void ProjectTest() {
//Arrange
var ProjectServiceMock = new Mock<IProjectService>();
var ProjectMock = new Mock<IProject>();
IProject project = ProjectMock.Object;
ProjectServiceMock
.Setup(x => x.CreateProject(It.IsAny<Path>(), "S1"))
.Returns(project);
//System under test
var addProjectViewModel = new AddProjectViewModel(ProjectServiceMock.Object);
//Act
addProjectViewModel.SomeMethodToTest();
//...assumption is that `CreateProject(new Path("C:"), "S1")` will get called within
//...the method under test
//Assert
//...now assert expected behavior
}
参考Moq Quickstart以更好地理解如何使用该模拟框架