ASP.NET Web API 单元测试 - 从返回 JsonResult 的控制器读取 Json 字符串



我有一个返回JsonResult(命名空间:System.Web.Http.Results)

public async Task<IHttpActionResult> GetConfig(string section, string group, string name)
{
var configurations = await _repository.GetConfig(section, group, name);
return Json(new { configurations = configurations.ToList() }, SerializerSettings);
}

我正在尝试对此方法进行单元测试。这是我到目前为止所拥有的

[Test]
public async void Should_Return_List_Of_Configs_Json()
{
var section= "ABC";
var group= "some group";
var name= "XYZ";
var response =  await controller.GetConfig(section, group, name);
Assert.IsNotNull(response);
}

我无法从上述方法中读取Json字符串,因为我看不到response.Content属性。对该方法的调用返回模拟响应。

有人可以帮助我解决这个问题吗?

如果我理解正确,你需要这样的东西(来源):

var response = await controller.GetConfig(section, group, name);
var message = await response.ExecuteAsync(CancellationToken.None);
var content = await message.Content.ReadAsStringAsync();
Assert.AreEqual("expected value", content);

您可以在单元测试中将 IHttpActionResult 强制转换为相应的 JsonResult。示例中使用的匿名类型应替换为 DTO 类型,以便可以在单元测试中正确转换它。这样的事情应该这样做

[Test]
public async void Should_Return_List_Of_Configs_Json()
{
var section= "ABC";
var group= "some group";
var name= "XYZ";
var response =  (JsonResult<List<YourDtoType>>)await controller.GetConfig(section, group, name);
Assert.IsNotNull(response);
}

第二种可能性是从 API 控制器返回实际类型,而不是 IHttpActionResult。诸如此类

public async Task<List<YourDtoType>> GetConfig(string section, string group, string name)
{
var configurations = await _repository.GetConfig(section, group, name);
return configurations.ToList();
}

最新更新