Dan*_*iel 64 c# moq mocking asp.net-mvc-3 wcf-web-api
我正在开发一个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)
}
Run Code Online (Sandbox Code Playgroud)
我需要Returns()方法来返回一个null对象,如果找不到资源,它将是实际API方法返回的对象.
我尝试在Returns()方法中将null作为参数发送但没有成功.
Jef*_*ata 182
您没有指出错误是什么,但这应该有效:
unitOfWork.Setup(m => m.PhysicalTests).Returns((IRepository<PhysicalTest>)null);
Run Code Online (Sandbox Code Playgroud)
我怀疑你试图调用它Returns(null),这会导致编译器抱怨,因为Returns它被重载并且它不知道应该调用哪个方法.转换为特定类型可消除歧义.
小智 12
rt 是方法的返回类型: FindById
repository.Setup(r => r.FindById(It.IsAny<int>())).Returns(Task.FromResult((rt)null));
Jor*_*tas 11
如果您收到如下错误:
您只需指定“Returns”方法的输入参数即可。看看我的例子:
_ = _fileStorage.Setup(x => x.LoadDocument(It.IsAny<string>())).Returns(value: null);
Run Code Online (Sandbox Code Playgroud)
Organization是方法的返回类型:Get
mockCache
.Setup(cache => cache.Get(It.IsAny<string>(), It.IsAny<string>(),It.IsAny<string>()))
.Returns(value: null as Organization);
Run Code Online (Sandbox Code Playgroud)