Reputation: 5627
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:
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?
Upvotes: 0
Views: 43
Reputation: 9499
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>;
Upvotes: 1