C
C#2y ago
yatta

How to assert HttpResponseMessage content in unit test [Answered]

Let's say I have 2 variable like this:
var result = await sender.SendAsync(request);
var testResMess = new HttpResponseMessage();
testResMess.Content = new StringContent("\"test message\"");
var result = await sender.SendAsync(request);
var testResMess = new HttpResponseMessage();
testResMess.Content = new StringContent("\"test message\"");
I want to test them in unit test to see if they're equal (which I know they are but I still need to do it in the unit test), so I do something like this:
Assert.AreEqual(testResMess.Content, result.Value);
Assert.AreEqual(testResMess.Content, result.Value);
csharp but the IDE yields The EqualTo constraint always fails as the actual and the expected value cannot be equal So i tried to change it to
Assert.AreEqual(testResMess.Content.ToString(), result.Value);
Assert.AreEqual(testResMess.Content.ToString(), result.Value);
And this time, I got the error: Expected string length 29 but was 12. Strings differ at index 0. Expected: "System.Net.Http.StringContent" But was: "test message" -----------^ At this rate, I have no idea is the problem I got and how I can solve them. I'm also new to C# Unit Testing so any help from expert would be really appriciate.
3 Replies
Lisa
Lisa2y ago
If you are comparing to a string, what's the point of building a stringcontent object and then comparing to that?
Assert.AreEqual("test message", result.Value);
Assert.AreEqual("test message", result.Value);
Or am I missing some context here?
Lisa
Lisa2y ago
Anyway, if you aren't actually building and just need to get the string value. .ToString() won't help you. https://learn.microsoft.com/en-us/dotnet/api/system.net.http.stringcontent?view=net-6.0 And look at the Read methods, those will get ya what you want.
StringContent Class (System.Net.Http)
Provides HTTP content based on a string.
Accord
Accord2y ago
✅ This post has been marked as answered!