1

I am facing issue in reading consents using Content.ReadAsAsync. Have a look at my code.

private HttpResponseMessage _responseMessage;
_responseMessage = UnitTestHelper.Get(string.Format("api/StudentController/Get/?StartDate={0}&EndDate={1}", DateTime.Now, DateTime.Now));
Assert.IsTrue(_responseMessage.IsSuccessStatusCode);
Assert.IsTrue(_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result.Count > 0);
var auditData = _responseMessage.Content.ReadAsStringAsync().Result;
_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;

Outcome of above code:

  • It successfully make post call, gets the result back.

  • Result.Count shows 1.

  • ReadAsStringAsync shows data in the following format.

    [{\"User\":\"Test\",\"Location\":\"MyCountry\",\"Class\":\"Grade1\",\"Time\":\"2016-07-06T07:26:11.183\",\"SchoolName\":\"ABC School System\"}]
    
  • Last line gives null. I am expecting a list here.

My Problem.

The following line of code always shows null. Whereas I am expecting to have list.

_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;

Why? What is wrong here?

TheKingPinMirza
  • 7,924
  • 6
  • 51
  • 81
  • Have a look here http://stackoverflow.com/questions/14205590/await-a-async-void-method-call-for-unit-testing – Barry O'Kane Jul 06 '16 at 07:45
  • You question is confusing. How can you get access to `Result.Count` if the prefixed object is `null`? – Nkosi Jul 06 '16 at 11:08
  • have a look at question again. updated. – TheKingPinMirza Jul 06 '16 at 14:18
  • @immirza, `ReadAsStringAsync` format is not JSON per say but rather a string that has been Json-encoded, hence the slashes. That would mean that what ever is returning the data is passing a JSON formatted string and not JSON. You understand? Show the action that maps to the url you are calling. – Nkosi Jul 28 '16 at 10:32

2 Answers2

3

The problem is that you're calling _responseMessage.Content.ReadAsAsync<List<StudentModel>>() twice. You should store the result in some variable and then work with it

var result = _responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;
Assert.IsTrue(result.Count > 0);
//do whatever needed with result

Also you'd better utilize async/await instead of calling .Result


To be more specific ReadAsAsync<T> uses internaly HttpContent.ReadAsStreamAsync which caches memory stream and once it is read Position stays at the end of the stream.

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
0

You have to update NewtonSoft.json.dll to the latest. This should work.