c# - How to get the Values from a Task returned through an API for Unit Testing
问题描述
I have created an API using ASP.NET MVC Core v2.1. One of my HttpGet
methods is set up as follows:
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
}
}
When unit testing this I can check that Ok was the response, but I really need to see the values of the configuration. I don't seem to be able to get this to work with the following:
[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();
}
At runtime, I can check that actionResult
has certain values that I am unable to code for. Is there something I am doing wrong? Or am I just thinking about this wrong? I would like to be able to do:
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);
}
}
推荐阅读
- r - 如何找到数据框或矩阵的最小值/最大值的位置(行/列)(R问题)
- node.js - 如何为嵌套在多个数组和对象中的对象显示 forEach
- r - 将 Shiny 合并到 Flexdashboard 中,以最少的闪亮代码实现动态文本输入
- arrays - 在 React JS 中过滤数组时未定义
- javascript - 如何通过单击从 div 中捕获数据
- c# - 是否还有办法以编程方式在 C#、VS2019 中获取最新版本的 TFVC 存储库?
- django - Django从模板的多个视图中调用相同的视图
- javascript - react-test-library 渲染一个在测试中声明的功能组件
- java - 是否可以使用 clon() 方法而不覆盖它
- javascript - Javascript:使用嵌套 for 循环比较嵌套数组中的元素