I am setting up a unit test and having trouble. I've seen the hello world examples, however my return type is more complex.
My controller is returning a list of objects. I am getting back an object with an array of objects as below:
Public Class ItemClass
{
public int Id,
public string Name
}
Public ContentResult GetItems(string criteria){
.
.
.
// List<ItemClass> myItemClass (this will containa list of several ItemClass)
// ItemInfo myItemInfo (this will contain a single object similar to the return data I have outlined below)
var model = new { ItemsList = myItemList, ItemInfo = myItemInfo}
return Content( [here i convert my `model` to json data]);
};
.
.
.
//TestMethod starts here:
//setup code
//act
var result = controller.GetList(criteria)
//assert
//this is where I'm having trouble
// result.content looks like this: "{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"
How can I deserialize result.content into an list of type ItemClass
so that I can do assertions against it? For example, I would like to assert that the result is not null, that there is a count of 2 items in the result and I would also want to test the existence of specific ids in the result. If there is a better way to do this type of test I'm open to suggestions.
I have tried the code. Looks like you have wrapped two different types inside a parent class. Please use the Parent type in the Deserialize method. Please refer to the code and image below. Many thanks.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class ItemClass
{
public int Id;
public string Name;
}
class ListInfo
{
public int Info1 { get; set; }
public string Info2 { get; set; }
}
class ItemCol
{
public List<ItemClass> ItemList { get; set; }
public ListInfo ListInfo { get; set; }
}
class Program
{
static void Main(string[] args)
{
var output = "{\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}], \"listInfo\": {\"info1\":1,\"info2\":\"bla\"}}";
var results = JsonConvert.DeserializeObject<ItemCol>(output);
Console.WriteLine("Hello World!");
}
}
}