我使用 ASP.NET MVC Core v2.1 创建了一个 API。我的一个HttpGet
方法设置如下:
public async Task<IActionResult> GetConfiguration([FromRoute] int? id)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
..... // Some code here
return Ok(configuration);
}
catch (Exception ex)
{
... // Some code here
}
}
当进行单元测试时,我可以检查响应是否为“Ok”,但我确实需要查看配置的值。我似乎无法让它与以下内容一起使用:
[TestMethod]
public void ConfigurationSearchGetTest()
{
var context = GetContextWithData();
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
var actionResult = controller.GetConfiguration(12);
Assert.IsTrue(true);
context.Dispose();
}
在运行时,我可以检查actionResult
有某些我无法编码的值。我做错了什么吗?或者我只是想错了?我希望能够做到:
Assert.AreEqual(12, actionResult.Values.ConfigurationId);
您无需更改返回类型即可获得经过测试的控制器。
IActionResult
是所有其他类型的基本类型。
将结果转换为预期类型并将返回值与预期进行比较。
由于您正在测试异步方法,因此也使测试方法异步。
[TestMethod]
public async Task ConfigurationSearchGetTest()
{
using (var context = GetContextWithData())
{
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
var actionResult = await controller.GetConfiguration(12);
var okResult = actionResult as OkObjectResult;
var actualConfiguration = okResult.Value as Configuration;
// Now you can compare with expected values
actualConfuguration.Should().BeEquivalentTo(expected);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)