Reputation: 2569
In my test I have the result of type HttpRequestMessage
and I need to assert that it's property Content
is set to correct object.
The problem is that HttpRequestMessage.Content
has a different (base) type than the object I want to compare with and I can't use ShouldBeEquivalentTo and Including like this:
HttpRequestMessage result = ...
result.Content.ShouldBeEquivalentTo (new ObjectContent (obj.GetType (), obj, new JsonMediaTypeFormatter ()),
options => options.Including (x => x.Value));
This does not compile because options working with Content property type (which is HttpContent
) and not with ObjectContent
.
The only way I found is to have two assertions like this:
result.Should ().BeOfType<ObjectContent> ();
((ObjectContent) result.Content).ShouldBeEquivalentTo (new ObjectContent (obj.GetType (), obj, new JsonMediaTypeFormatter ()),
options => options.Including (x => x.Value));
Is there a better way to do it? Maybe some kind of BeOfType
which returns casted object fluent assertion instead of the base one?
Upvotes: 1
Views: 1225
Reputation: 12780
I'm not sure of a simpler way, but if you are trying to avoid the ugly code in multiple places, an extension method might work well:
Something like (I'm not sure if this will compile as is):
public static class ShouldBeHelper
{
public static void ShouldBeSameContent(this HttpRequestMessage result, object expected)
{
result.Should().BeOfType<ObjectContent>();
((ObjectContent)result.Content).ShouldBeEquivalentTo(new ObjectContent(expected.GetType(), expected, new JsonMediaTypeFormatter(),
options => options.Including(x => x.Value));
}
}
Upvotes: 1