如何在UnitTest中获取返回的JsonResult内的数据?

时间:2017-11-02 00:14:18

标签: c# unit-testing jsonresult

我有一个控制器方法,它返回一个像这样的JsonResult:

    public ActionResult GetZipByState(string stateId)
    {
        var result =
            _mediator.Send<List<ZipCodeModel>>(new ZipCodeByStateQuery()
            {
                StateId = stateId
            });

        return Json(new { ZipCodes = result }, JsonRequestBehavior.AllowGet);
    }

然后我进行了单元测试:

    [Fact]
    public void GetZipByState_CanGetZipCodesByStateId()
    {
        // Arrange
        _mockMediator.Setup(m => m.Send<List<ZipCodeModel>>(It.Is<ZipCodeByStateQuery>(plist => plist.StateId == "VA")))
           .Returns(new List<ZipCodeModel>()
           {
                new ZipCodeModel(){ ZipCodeId = "7690", ZipCode = "24210" },
                new ZipCodeModel(){ ZipCodeId = "7691", ZipCode = "24211" },
                new ZipCodeModel(){ ZipCodeId = "7692", ZipCode = "24212" }
           });

        // Act
        //var actual = _controller.GetZipByState("VA");
        JsonResult actual = _controller.GetZipByState("VA") as JsonResult;
        List<ZipCodeModel> result = actual.Data as List<ZipCodeModel>;

        // Assert
        Assert.Equal("24211", (dynamic)actual.Data);
    }

我可以在我的Json下看到我需要的数据:

在此屏幕截图中的actual.Data.ZipCodes [1]:

enter image description here

但是当我尝试将actual.Data放入结果var然后执行断言时,它告诉我结果是null。

你打算怎么做?

1 个答案:

答案 0 :(得分:1)

你的问题是你输错了类型。

这一行: body>.grid { height: 100%; background-color: #DADADA; } .image { margin-top: -100px; } .column { max-width: 450px; } 应更改为

List<ZipCodeModel> result = actual.Data as List<ZipCodeModel>;