Xunit doesn't have an Assert.Fail() operation
In many unit-test frameworks there is an explicit Assert-operation for triggering a test-failure in a context where something is wrong (for whatever reason) but there's nothing concrete to assert on.
This typically is implemented as Assert.Fail(message). The best you can do in xUnit right now to emulate that is using Assert.True(false, "Message"), but this can cause confusion and noise in the test-output:
message
Expected: True
Actual: False
In the case of an explicit failure the only wanted output should be:
message
It would be nice if xUnit added an Assert.Fail(string message) operation which didn't include unnecessary assert-information,
Historically, we have not supported Assert.Fail for the same reason our asserts don't (usually) have error messages: because we believe that a custom assertion is a better option than general purpose failure. Our workaround for this is Assert.True(false, message).
But it’s not a good workaround. And it makes migrating from other frameworks much harder than it needs to be.
And all the reasons provided against ‘Assert.Fail()’ clearly apply even more so against ‘Assert.True(false)’.
It’s not a good workaround, and it’s a even worse migration story.
I’d love to have you reconsider this issue. The wort is going to be there either way, so let’s choose the least ugly way to deal with it.
We provide the assertion library as both a Git submodule as a source-level NuGet package, in the event that you'd like to extend it for your own personal use (f.e., to add Fail).
We provide the assertion library as both a Git submodule as a source-level NuGet package, in the event that you'd like to extend it for your own personal use (f.e., to add Fail).
That's not really ergonomical though, and again, another pain users will encounter/figure out/solve when trying to migrate from other test-frameworks, something which no doubt will reduce Xunit-adoption.
As a general open-source proponent, I value trying to make it easier for new contributors to join in on "my" projects, and I value projects which feels welcoming for me to join. I see that as a necessity for a project to stay healthy, and not go stale once the "old" contributors decide to retire.
I like to think a community-project like Xunit should be such a community and reflect the wishes of the community. But if you unilaterally insist this is something you don't want and you wont add, I guess I'll just close all my issues and PRs and limit my involvement in the future.
Just be aware by making such decisions, you've also decided to turn away contributors which could help grow Xunit in the future.
Your call.
using Xunit;
using Xunit.Sdk;
public class T
{
[Fact]
public void AlwaysFail()
{
throw new XunitException("Error message.");
}
}
I'd like to use Assert.Fail(message) when using functional programming constructs in C# code, for example:
// Act
Optional<Response> response = sut.GetResponse();
// Assert
response.Match(
some: x => Assert.True(x.SuccessStatusCode),
none: () => Assert.Fail("Response should have been received."));
Not having Assert.Fail() makes unit test code stylistically different than actual program code (or you have to use ugly workarounds), which is confusing. As my own workaround, I have custom failure method that allows me to write something close to above. But I would prefer Assert.Fail() out-of-the-box.
without Assert.Fail(), how do you propose someone assert that a method either throws a certain type of exception, or no exception at all?
try {
....
} catch (MyException) {
} catch (Exception) {
Assert.Fail();
}
var exn = Record.Exception(() => ...)
Assert....
or
var exn = Assert.Throws<MyExcception>(() => ...)
// (or ignore the return value)
I am currently dealing with a situation in which some of our test code runs within a wrapper of a framework we are using. This framework is very nice and catches all exceptions for us, that means that my test can never fail. Since we also use a custom test wrapper between the framework and the actual application code I was hoping to bypass the nice framework with some sort of hard exception using an xUnit call.
Currently my only workaround is to call Environment.Exit , but that only shows the test as incomplete and won't show the developers the stack trace, which is obviously far from ideal.
So my 2 cents on this discussion would be that Assert.Fail could perhaps facilitate this special purpose.
Nope, Assert.Fail, like any Assert, equally depends on throwing - this 'debate' is entirely about semantics of whether you should be allowed to say "Well actually, I should not have to be express my assertion in concrete terms"
My takeaway here is inline the 'custom assertion' :
throw new XunitException()is the replacement forAssert.Fail(), notAssert.True(false);throw new XunitException(message)is the replacement forAssert.Fail(message), notAssert.True(false,message);
I was about to migrate my MSTest project to xUnit.NET:
- No Assert.Fail
- No Assert.Null(obj, message)
What the heck. Thanks that was enough, will never use this tool.
I agree that Assert.Fail is not a very descriptive assertion for "program should never get here"-type assertions, so my solution-of-kinds (abusing AppDomain.CurrentDomain.FirstChanceException) is this:
Click to see
public sealed class ThrowMonitor : IDisposable
{
public static ThrowMonitor Create<TException>( out ShouldNotAction shouldNotHaveReachedThisPoint )
where TException : Exception
{
return new ThrowMonitor( typeof(TException), out shouldNotHaveReachedThisPoint );
}
private readonly EventHandler<FirstChanceExceptionEventArgs> handlerDelegate;
private readonly Type expectedExceptionType;
private readonly List<Exception> actualThrownExceptions = new List<Exception>();
public ThrowMonitor()
: this( expectedExceptionType: typeof(Exception) )
{
}
public ThrowMonitor( Type? expectedExceptionType )
{
this.handlerDelegate = new EventHandler<FirstChanceExceptionEventArgs>( this.CurrentDomain_FirstChanceException );
this.expectedExceptionType = expectedExceptionType ?? typeof(Exception);
AppDomain.CurrentDomain.FirstChanceException += this.handlerDelegate;
}
public ThrowMonitor( Type? expectedExceptionType, out ShouldNotAction shouldNotHaveReachedThisPoint )
: this( expectedExceptionType )
{
shouldNotHaveReachedThisPoint = this.AssertShouldNotReachThisPoint;
}
private void CurrentDomain_FirstChanceException( Object? sender, FirstChanceExceptionEventArgs e )
{
if( !( e.Exception is Xunit.Sdk.XunitException ) )
{
this.actualThrownExceptions.Add( e.Exception );
}
}
public void Dispose()
{
AppDomain.CurrentDomain.FirstChanceException -= this.handlerDelegate;
if( this.actualThrownExceptions.Count > 0 )
{
if( this.actualThrownExceptions.Any( ex => this.expectedExceptionType.IsAssignableFrom( ex.GetType() ) ) )
{
// OK
}
else
{
Exception lastException = this.actualThrownExceptions.Last();
throw new Xunit.Sdk.ThrowsException( expectedType: this.expectedExceptionType, actual: lastException );
}
}
else
{
// No exception was thrown, so complain:
throw new Xunit.Sdk.ThrowsException( expectedType: this.expectedExceptionType );
}
}
public void AssertShouldNotReachThisPoint(
String? message = null,
[CallerMemberName] String? memberName = null,
[CallerFilePath ] String? callerFile = null,
[CallerLineNumber] Int32 lineNumber = 0
)
{
if( String.IsNullOrWhiteSpace( message ) )
{
// This will use the default message `"(No exception was thrown)"`.
throw new Xunit.Sdk.ThrowsException( expectedType: this.expectedExceptionType );
}
else
{
throw new NothingThrownException( expectedType: this.expectedExceptionType, message );
}
}
private sealed class NothingThrownException : Xunit.Sdk.ThrowsException
{
public NothingThrownException( Type expectedType, String message )
: base(
expected : expectedType,
actual : message,
actualMessage : null,
stackTrace : null,
innerException: null
)
{
}
}
}
public delegate void ShouldNotAction(
String? message = null,
[CallerMemberName] String? memberName = null,
[CallerFilePath ] String? callerFile = null,
[CallerLineNumber] Int32 lineNumber = 0
);
Used like so:
[Fact]
public void Should_fail_to_deserialize_tenant_response_using_V19_DTOs()
{
String json = File.ReadAllText( path: _fileName );
try
{
using( ThrowMonitor.Create<JsonException>( out ShouldNotAction shouldNotHaveReachedThisPoint ) )
{
V19.TenantDto deserialized = JsonConvert.DeserializeObject<V19.TenantDto>( json );
shouldNotHaveReachedThisPoint();
}
}
catch( JsonException jsonEx ) when ( jsonEx.Message == @"Required property 'resourceInstanceId' not found in JSON. Path 'shops[4].logoResource.resourceInstances[0]', line 167, position 11." )
{
}
}
The nice thing about this approach, compared to Assert.Throws is that it doesn't muddy your stack-trace or require you to invoke your code via a delegate.
[Fact]
public void MatchWithResult_ShouldReturnTheSomeBranch_IfOptionIsNotEmpty()
{
var shouldNotBeCalled = Substitute.For<Func<int>>();
var res = Some(Value).Match(
some: v => v + 1,
none: shouldNotBeCalled);
res.ShouldBe(Value + 1);
shouldNotBeCalled.DidNotReceiveWithAnyArgs()();
}
This example uses NSubstitute.
I am currently dealing with a situation in which some of our test code runs within a wrapper of a framework we are using. This framework is very nice and catches all exceptions for us, that means that my test can never fail. Since we also use a custom test wrapper between the framework and the actual application code I was hoping to bypass the nice framework with some sort of hard exception using an xUnit call.
Currently my only workaround is to call
Environment.Exit, but that only shows the test as incomplete and won't show the developers the stack trace, which is obviously far from ideal.So my 2 cents on this discussion would be that Assert.Fail could perhaps facilitate this special purpose.
I'd like to know how do you solve this situation? @HugoPeters1024 Cause I am dealing with this now....
For anyone landing here, Assert.Fail is now available per https://github.com/xunit/xunit/issues/2609#issuecomment-1399639884