Moq 对象返回方法,应返回空对象

我正在开发一个 Web API,我想到的一个测试是,如果客户端使用物理测试 ID (Physical Test 是我正在寻找的资源)执行 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)
}

我需要 Return ()方法来返回一个 null 对象,如果没有找到资源,那么实际的 API 方法将返回这个空对象。

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

96491 次浏览

You don't indicate what the error was, but this should work:

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

I suspect you tried to call it with Returns(null), which causes the compiler to complain since Returns is overloaded and it doesn't know which method should be called. Casting to a specific type removes the ambiguity.

rt is a return type of method: FindById

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

You could try this:

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

If you are receiving an error like this:

enter image description here

You just need to specify the input parameter of 'Returns' method. Take a look in my example:

_ = _fileStorage.Setup(x => x.LoadDocument(It.IsAny<string>())).Returns(value: null);

Organization is a return type of method: Get

mockCache
.Setup(cache => cache.Get(It.IsAny<string>(), It.IsAny<string>(),It.IsAny<string>()))
.Returns(value: null as Organization);

You're too close, you only need to pass the return type as generic type like so

repository.Setup(r => r.FindById(It.IsAny<int>())).Returns<IRepository<PhysicalTest>>(null);