首页 > 解决方案 > 单元测试中模拟资源的参数是否重要?

问题描述

我的问题与我们何时模拟外部资源有关(在我的情况下,它们是外部 API 和数据库)。

假设我希望请求的结果是某个对象,基于我提供的输入(例如 ID)。在测试时,我倾向于使用It.IsAny<int>, 而不是编写真实 ID,因为我认为它是不必要的,因为它是一个模拟对象,我主要关心的是从该方法返回的内容。

服务方法.cs

public async IActionResult CreateObject(Guid? objectID){
   var response = await myApi.GetObjectFromApi(objectID);
   
   if(!response.IsSuccessStatusCode){
      throw new HttpResponseException(response.StatusCode);
   }
   return Ok(response);
}

测试

[Test]
public void CreateObject_ReturnsSuccess(){
   // mocked myApi dependency
   _myApiMock
         .Setup(x=>x.GetObjectFromApi(It.IsAny<Guid>())
         .Returns(new HttpResponseMessage(){ StatusCode = HttpStatusCode.OK }

   var response = CreateObject(Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f"));

   Assert.That(response.StatusCode, Is.Equal(HttpStatusCode.OK));
}

我的问题是:由于我在模拟 API 依赖项,除了可读性之外,使用实际的 Guid 值还有什么意义吗?(行-> .Setup(x=>x.GetObjectFromApi(It.IsAny<Guid>())

标签: c#apiunit-testingmocking

解决方案


@Jonrsharpe 在评论中给出的答案帮助我理解了问题并为我的用例实施了解决方案。

"Really what matters is what's communicated about your expectations for the code you're testing. To me, It.IsAny<Guid>() suggests "we can't control this exactly" - maybe the code under test is creating its own GUID, which will be different each time. But in this case you're passing it in, so if you extract Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f") to the start of the test and use that it's clear that you expect the same GUID to be passed through. If it's not, you'll find out." - Jonrsharpe


推荐阅读