Search code examples
c#fluent-assertions

How to create custom FluentAssertion error messages?


I have a test that looks something like this:

using (new AssertionScope())
{
    foreach (var parameterType in parameterTypes)
    {
        var fooType = typeof(IFoo<>);
        var genericType = providerType.MakeGenericType(parameterType);

        serviceProvider
            .GetService(fooType)
            .Should()
            .NotBeNull($"all Foo types should be registered");
    }
}

Test failure results in this message:

Expected serviceProvider.GetService(genericProviderType) not to be <null> because all Foo types should be registered.

However, I would like the message to say:

Expected IFoo<MyParameter> not to be <null> because all Foo types should be registered.

(I already have a method to prettify the typename - type.GetPrettyName)

Going by the documentation and source code, it looks like I need to find a way to modify the Subject/Identifier (not 100% sure) but I can't find a way to do that.

I also tried using a Lazy context function in the AssertionScope constructor but this results in a modified closure.


Solution

  • using (new AssertionScope())
    {
        foreach (var parameterType in parameterTypes)
        {
            var fooType = typeof(IFoo<>);
            var genericType = providerType.MakeGenericType(parameterType);
    
            using _ = new AssertionScope(fooType.GetPrettyName());
           
            serviceProvider
                .GetService(fooType)
                .Should()
                .NotBeNull($"all Foo types should be registered");
        }
    }