1

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?

Michael Logutov
  • 2,551
  • 4
  • 28
  • 32
  • Can't use the overload that provides you with an `ISubjectInfo` object? Then you can use a text-based matched on the property path. – Dennis Doomen Jan 28 '14 at 11:35
  • Dennis, if you mean reflection, then I think it would be even more uglier. – Michael Logutov Jan 28 '14 at 16:10
  • No no, there's an overload that provides you with a Func<> to an ISubjectInfo. And that object provides access to the full property path that you might be able to get the same effect. Look at the example in https://github.com/dennisdoomen/fluentassertions/blob/master/FluentAssertions.Specs/EquivalencySpecs.cs at line 533. – Dennis Doomen Jan 29 '14 at 12:49
  • Ah, didn't know that. But it's magic strings which are subject to break on refactoring :( – Michael Logutov Jan 29 '14 at 18:06
  • I agree. But that's why have unit tests in the first place ;-) – Dennis Doomen Jan 30 '14 at 12:22

1 Answers1

1

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));
    }
}
Rick Love
  • 12,519
  • 4
  • 28
  • 27
  • Well, yeah, we can use extensions but I was thinking that it should be possible with the library itself instead of writing extensions all the time. – Michael Logutov Jan 28 '14 at 16:11