c# - 单元测试中模拟资源的参数是否重要?
问题描述
我的问题与我们何时模拟外部资源有关(在我的情况下,它们是外部 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>())
)
解决方案
@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
推荐阅读
- python-3.x - Python 多处理似乎正在影响程序的结果
- python - 数据帧的平均值
- javascript - How to validate form based on values and submit call out to another page accordingly?
- c++ - 如何在 C++ 中输出分栏符
- bash - 查找内部管道内的 awk 命令
- node.js - 在一个响应中流式传输多个文件 - Node.js
- php - 如何使用 PHP 修复 API 不通过 GET 命令返回结果
- javascript - Sequelize MySQL 从其他表更新值副本
- css - 通过javascript添加时复选框未使用正确的gentelella css呈现
- php - PHP - 以随机顺序显示目录文件夹