Assert an Exception Using Xunit

Assert an Exception using XUnit

The Assert.Throws expression will catch the exception and assert the type. You are however calling the method under test outside of the assert expression and thus failing the test case.

[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException()
{
//arrange
ProfileRepository profiles = new ProfileRepository();
// act & assert
Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID(""));
}

If bent on following AAA you can extract the action into its own variable.

[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException()
{
//arrange
ProfileRepository profiles = new ProfileRepository();
//act
Action act = () => profiles.GetSettingsForUserID("");
//assert
ArgumentException exception = Assert.Throws<ArgumentException>(act);
//The thrown exception can be used for even more detailed assertions.
Assert.Equal("expected error message here", exception.Message);
}

Note how the exception can also be used for more detailed assertions

If testing asynchronously, Assert.ThrowsAsync follows similarly to the previously given example, except that the assertion should be awaited,

public async Task Some_Async_Test() {

//...

//Act
Func<Task> act = () => subject.SomeMethodAsync();

//Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(act);

//...
}

XUnit: How to assert exception thrown by the controller in ASP.NET Core

Use Assert.ThrowsAsync (the asynchronous counterpart of Assert.Throws) to assert that an exception of a particular type is thrown.

In your case you'll want something like:

var ex = await Assert.ThrowsAsync<HttpException>(async () => await emailController.AppendEmailBase64Dto(testEmailBase64Dto));

Obviously adjust 'HttpException' to whatever type of exception you're expecting.
You're not going to be able to check the return type in the same test (because AppendEmailBase64Dto will not return when an exception is thrown), so you'll need to test the exception in a separate test.

Test Exceptions in Xunit ()

The test is not awaiting the Task<Exception> returned from Record.ExceptionAsync so the following assertion is actually being done on the Task itself.

Also the method under test consumes the DocumentClientException and throws a new exception of InvalidOperationException so that is the type that should be expected.

[Fact]
public async virtual Task Test_Exception() {
//Arrange
var queryString = "SELECT * FROM c";

//Act
var exception = await Record.ExceptionAsync(() =>
classname.RunSQLQueryAsync(queryString));

//Assert
Assert.NotNull(exception);
Assert.IsType<InvalidOperationException>(exception);
}

Note the await before the Record.ExceptionAsync

The assumption is also that the class under test has been setup with a mocked dependency that will throw the desired exception in the //do something part of the provided snippet.

how to throw an exception using Assert.Throws in Xunit

You need to capture the exception result during your act:

  // Act
var result = Assert.Throws<ArgumentException(() => Test().Mapping(risk, request));

// Assert
result.Message.Should().Be(expected);

Can't Assert exception in async method with Xunit

Make your test method asynchronous and await the assertion:

[Fact]
public async Task ProbeTest()
{
// Arrange
var probe = new Probe();

// Act
Func<Task> action = async () => await probe.GetJob();

// Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(action);
Assert.Contains("Trouble with Project.", ex.Message);
}

xUnit Assert.Throws and Record.Exception does not catch exception

The xUnit Assert.Throws & Record.Exception behavior is as expected while I Run Tests.

Issue is with debugging tests.

I was able to debug the test by stepping over from the exception thrown line. After you see the control stopped at the line, press F8 or F5 to continue and test will be executed.

throw new Exception("Cannot add a unknown friend.");

How do I use Assert to verify that an exception has been thrown with MSTest?

For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.

Sample from the documentation here: A Unit Testing Walkthrough with Visual Studio Team Test

[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}

Exception message in xunit includes parameter so my test fails

You can create the exact same exception and use its message property. Like the code below

[Fact]
public void CannotWithdrawLessThanZero()
{
// Arrange
var account = new Account("User", 23);
var expectedException = new System.ArgumentOutOfRangeException("amount", AmountLessThanZeroMessage);

// Act
account.DepositCash(100);
var thrownException = Assert.Throws<ArgumentOutOfRangeException>(() => account.WithdrawCash(-10));

// Assert
Assert.Equal(expectedException.Message, thrownException.Message);
}

ExpectedException xunit .net core

Use Assert.Throws on code where exception expected:

[Fact]
public void TestMethod1_Error_twoMathces()
{
var message = "some text";
var parser = new MessageTypeParser();
Assert.Throws<MessageTypeParserException>(() => parser.GetType(message));
}


Related Topics



Leave a reply



Submit