How to override "context" with AssertionScope #1693
-
I love creating domain specific assertion extensions, but sometimes run into issues where I cannot get my validation messages to format nicely. E.g., using (.NET 6 rc.1, FluentAssertions 6.1.x, xunit 2.4.x): using FluentAssertions;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
using Xunit;
using Xunit.Sdk;
namespace ScopeAssertions;
public class Foo
{
public string? Name { get; set; }
public object? Content { get; set; }
}
public class FooAssertions : ReferenceTypeAssertions<Foo, FooAssertions>
{
public FooAssertions(Foo instance) : base(instance) { }
protected override string Identifier => "foo";
public AndConstraint<FooAssertions> WithContent<T>(T content, string because = "", params object[] becauseArgs)
{
using (new AssertionScope($"content of {Identifier}"))
{
Subject.Content.Should().BeAssignableTo<T>().And.BeEquivalentTo(content, because, becauseArgs);
}
return new(this);
}
}
public class UnitTest1
{
[Fact]
public void Test()
{
var target = new Foo { Name = "Foo", Content = "Bar" };
var sut = new FooAssertions(target);
sut.Invoking(x => x.WithContent("Baz"))
.Should()
.Throw<XunitException>()
.WithMessage(@"Expected content of foo to be ""Baz"", but ""Bar"" differs near ""r"" (index 2).");
}
} Here I expect my custom assertion scope's context string to be used, but it does not seem to be. Running the test produces this output:
So, how do I control the failure message in this particular case? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
You need to add the |
Beta Was this translation helpful? Give feedback.
-
Not really. The best you could do is to call |
Beta Was this translation helpful? Give feedback.
Not really. The best you could do is to call
DiscardFailures
on the assertion scope, right after theBeEquivalentTo
call. It'll give you the failure messages it was going to throw at the end of the using block. Then you could replace theSubject.Value
with something you need and do anExecute.Assertion
to throw your final message.