85

我正在开发一个 Web API,我想出的测试之一是,如果客户端使用物理测试 ID 进行 GET 操作(物理测试是我正在寻找的资源)并且找不到物理测试,Web API 应返回 404 状态。

现在,我正在使用 moq 框架进行测试,并且我有以下代码:

[TestMethod]
public void then_if_physical_test_not_found_return_not_found_status()
{
    var unitOfWork = new Mock<IUnitOfWork>();
    var repository = new Mock<IRepository<PhysicalTest>>();
    repository.Setup(r => r.FindById(It.IsAny<int>())).Returns();
    unitOfWork.Setup(m => m.PhysicalTests).Returns(repository.Object);
    var pt = new PhysicalTestResource(unitOfWork.Object);
    HttpResponseMessage<PhysicalTest> response = pt.GetPhysicalTest(43);
    Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode)
}

我需要 Returns() 方法返回一个空对象,如果找不到资源,这将是实际 API 方法返回的内容。

我尝试在 Returns() 方法中将 null 作为参数发送,但没有成功。

4

5 回答 5

253

您没有指出错误是什么,但这应该有效:

unitOfWork.Setup(m => m.PhysicalTests).Returns((IRepository<PhysicalTest>)null);

我怀疑您尝试使用 调用它Returns(null),这会导致编译器抱怨,因为Returns它已重载并且它不知道应该调用哪个方法。转换为特定类型可以消除歧义。

于 2011-10-27T17:23:37.807 回答
12

rt是方法的返回类型:FindById

repository.Setup(r => r.FindById(It.IsAny<int>())).Returns(Task.FromResult((rt)null));

于 2018-07-31T10:37:42.917 回答
2

Organization是方法的返回类型:Get

mockCache
    .Setup(cache => cache.Get(It.IsAny<string>(), It.IsAny<string>(),It.IsAny<string>()))
    .Returns(value: null as Organization);
于 2021-12-04T13:32:58.867 回答
1

如果您收到这样的错误:

在此处输入图像描述

您只需要指定“返回”方法的输入参数。看看我的例子:

_ = _fileStorage.Setup(x => x.LoadDocument(It.IsAny<string>())).Returns(value: null);
于 2021-08-27T12:45:09.867 回答
0

你可以试试这个:

ref1.Setup(s => s.Method(It.IsAny<Ref2>(), It.IsAny<string>()))
     .Returns((Task<Ref3>)null);

ref1 = Mock Interface
Ref2 = Type request parameter
Ref3 = Type of return method mock
于 2021-05-21T19:33:05.073 回答