1

In my xUnit test case I am reading JSON from a file, loading it in string and passing it a function that is originally called by controller.

My controller is:

[HttpPost]
public List<SomeCls> Post([FromBody] object ds)
{      
    var result = Myservice.DoSomething(ds);
}

This controller API works fine, I tested by posting raw json via Postman. However, in my unit test when I read JSON from a file and pass it into Myservice.DoSomething(ds), I get error:

---- System.ArgumentException : Could not cast or convert from System.String to System.Collections.Generic.List`1[MyDataSet].

In my xUnit test, how to convert JSON string into an object similar to the one that gets passed into the controller method by POST request?

Dave Barnett
  • 2,045
  • 2
  • 16
  • 32
variable
  • 8,262
  • 9
  • 95
  • 215

2 Answers2

0

You need to deserialise the string to the object you want. This is done for you by the controller but you'll have to do it manually when unit testing. If you're using Json.Net (Newtonsoft) then the code will look something like this:

var yourObject = JsonConvert.DeserializeObject<List<MyDataSet>>(yourJsonString);
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
  • But at the controller level I dont specify anything for it to realize that it should map to MyDataSet. So how does it happen automatically? – variable Jun 13 '20 at 23:05
  • Model binding - have a read through https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1 for examples for controllers and razor pages. – SBFrancies Jun 13 '20 at 23:09
0

Why not deserialize the object first using Newtonsoft.Json and something like...

List<type> value = JsonConvert.DeserializeObject<type>(ds); 
var result = Myservice.DoSomething(value);
Mark
  • 93
  • 5