0

I have a controller method that returns a JsonResult like this:

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

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

Then I have this Unit Test:

    [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);
    }

I can see the data I need to get to in my Json under:

actual.Data.ZipCodes[1] in this screen shot:

enter image description here

But when I try to put the actual.Data into the result var and then do the assert, it is telling me that result is null.

How are you supposed to do this?

Sam
  • 4,766
  • 11
  • 50
  • 76
  • You cannot simply cast jsonresult data to any type. You need to use json serializer to deserialize it to the target type object – Chetan Nov 02 '17 at 00:19
  • Looks like it is the same as here. [https://stackoverflow.com/questions/25875658/converting-jsonresult-into-a-different-object-in-c-sharp](https://stackoverflow.com/questions/25875658/converting-jsonresult-into-a-different-object-in-c-sharp) – Cedar Nov 02 '17 at 03:02
  • Take a look at this answer I gave to a similar question https://stackoverflow.com/a/38446754/5233410 – Nkosi Nov 02 '17 at 09:57

1 Answers1

1

Your problem is that you are casting to wrong type.

This line here: List<ZipCodeModel> result = actual.Data as List<ZipCodeModel>; should be changed to

var result = actual.Data.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(x => x.Name == "ZipCodes")
.GetValue(actual.Data) as List<ZipCodeModel>;
zaitsman
  • 8,984
  • 6
  • 47
  • 79