如何从C#中返回IHttpActionResult的控制器获取JSON格式的数据?

时间:2018-02-06 10:39:45

标签: c# unit-testing asp.net-web-api2 nunit moq

我有一个使用Newtonsoft.Json将IEnumerable转换为JSON格式的控制器。

[Route("")]
public IHttpActionResult Get()
{
    IEnumerable<Product> productList = ProductService.GetAllProducts();
    if (!productList.Any())
        return Ok();

    return Json(productList, new JsonSerializerSettings
    {
        ContractResolver = new WebContractResolver(),
        Converters = new List<JsonConverter> { new TrimStringDataConverter() }
    });
}

当我通过POSTMAN点击API终点时,它会给我预期的JSON数据。

[
    {
        "code": "prod101",
        "title": "LAPTOP"
    },
    {
        "code": "prod102",
        "title": "MOBILE"
    }
]

现在,我正在为控制器编写单元测试(NUnit),我想在单元测试方法中获取这个JSON格式的数据。 我能够获得IEnumerable -

IHttpActionResult actionResult = mockProductControllerClient.Get();
JsonResult<IEnumerable<Product>> contentResult = actionResult as JsonResult<IEnumerable<Product>>;
IEnumerable<Product> data = contentResult.Content;

我需要在单元测试方法中使用与在POSTMAN中接收的完全相同的数据,即JSON数据

1 个答案:

答案 0 :(得分:1)

我找到了答案 -

IHttpActionResult保存了SerializerSettings,当响应处理掉时,可能会在管道中应用。

在单元测试中,由于我们从控制器(即管道中间)获取数据,因此我们必须自己应用SerializerSettings。 因此,第一步是从动作结果中提取IEnumerable -

IHttpActionResult actionResult = MockController.Get();
JsonResult<IEnumerable<Product>> contentResult = actionResult as JsonResult<IEnumerable<Product>>;

然后,应用序列化设置并获取您的json -

string responseString = JsonConvert.SerializeObject(contentResult.Content, contentResult.SerializerSettings);
JArray responseJson = JArray.Parse(responseString);

希望,这会有所帮助。