If I have a controller like this:
[HttpPost]
public JsonResult FindStuff(string query)
{
var results = _repo.GetStuff(query);
var jsonResult = results
I extend the solution from Matt Greer and come up with this small extension:
public static JsonResult IsJson(this ActionResult result)
{
Assert.IsInstanceOf(result);
return (JsonResult) result;
}
public static JsonResult WithModel(this JsonResult result, object model)
{
var props = model.GetType().GetProperties();
foreach (var prop in props)
{
var mv = model.GetReflectedProperty(prop.Name);
var expected = result.Data.GetReflectedProperty(prop.Name);
Assert.AreEqual(expected, mv);
}
return result;
}
And i just run the unittest as this: - Set the expected data result:
var expected = new
{
Success = false,
Message = "Name is required"
};
- Assert the result:
// Assert
result.IsJson().WithModel(expected);