gpt4 book ai didi

c# - 对继承类的最小起订量测试总是返回 null

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:21 25 4
gpt4 key购买 nike

我在为实现存储库模式的 Controller 设置单元测试时遇到问题。我想检查 Controller 的返回值。为存储库设置我的 Mock 时,继承的 IRepository 方法总是返回 null。我期待看到在我的 .ReturnsAsync("test")

中定义的字符串“test”

存储库

public interface IRepository
{
Task<T> Get<T>(string storedProcedure, object template);

Task<T> Get<T>(string sql, CommandType commandType, object template);
}

public interface ITARRepository : IRepository
{
// other methods
...
}

Controller

private readonly ITARRepository Repository;

public async Task<IActionResult> GetTARTrackerResponse(long id)
{
try
{
var result = await Repository.Get<string>("spName", new { @Params = id });

return Ok(result);
}
catch (Exception e)
{
// logged
...

return StatusCode((int)HttpStatusCode.InternalServerError);
}
}

测试

[Fact]
public async Task Returns_OK_With_Tar_Tracker_Response()
{
//arrange
var mockRepo = new Mock<ITARRepository>();

mockRepo
.Setup(repo => repo.Get<string>("storedproc", new { test = 12345 }))
.ReturnsAsync("test");

var controller = new TARTrackerController(Logger, mockRepo.Object);

//act
var result = await controller.GetTARTrackerResponse(12345);
var ObjectResult = result as ObjectResult;

//assert
Assert.IsType<OkObjectResult>(result);
Assert.IsType<string>(ObjectResult.Value.GetType());
}

最佳答案

设置中的参数匹配器与被测对象中实际调用的匹配器不匹配,因此模拟在执行测试时调用时不会按预期运行。

主题正在调用

var result = await Repository.Get<string>("spName", new { @Params = id });

虽然模拟的依赖期望

.Setup(repo => repo.Get<string>("storedproc", new { test = 12345 }))

使用 It.IsAny<T>() 配置模拟以完全匹配预期的内容或放松预期的匹配

[Fact]
public async Task Returns_OK_With_Tar_Tracker_Response() {
//arrange
string expected = "test";
var mockRepo = new Mock<ITARRepository>();
mockRepo
.Setup(repo => repo.Get<string>(It.IsAny<string>(), It.IsAny<object>()))
.ReturnsAsync(expected);

var controller = new TARTrackerController(Logger, mockRepo.Object);

//act
var result = await controller.GetTARTrackerResponse(12345);

//assert
OkObjectResult objectResult = Assert.IsType<OkObjectResult>(result);
string actual = Assert.IsType<string>(objectResult.Value);
Assert.Equal(expected, actual);
}

关于c# - 对继承类的最小起订量测试总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com