I am trying to write Xunit test on this method:
public async Task<IEnumerable<T>> RunSQLQueryAsync(string queryString)
{
try
{
//do something
}
catch (DocumentClientException e)
{
throw new InvalidOperationException(e);
}
}
Here's the unit test:
[Fact]
public async virtual Task Test_Exception()
{
var queryString = "SELECT * FROM c";
var exception = Record.ExceptionAsync(async () => await classname.RunSQLQueryAsync(queryString));
Assert.NotNull(exception);
Assert.IsType<DocumentClientException>(exception);
}
But the method failed and it says:
Message: Assert.IsType() Failure Expected: System.DocumentClientException Actual:
System.Threading.Tasks.Task`1[[System.Exception, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxx]]
When I debugged the test, it doesn't go to the catch block. So my question is how to make the unit test expects the method RunSQLQueryAsync
to have DocumentClientException
?
Assert. Throws<Exception>(() => SomethingThatThrowsAnException()); If the method SomethingThatThrowsAnException() from the above throws an exception the assertion passes, if it does not throw an exception, the assertion will fail and thereby the test fails. It is as simple as that.
In xUnit, a test fixture is all the things we need to have in place in order to run a test and expect a particular outcome. Some people call this the test context.
XUnit by default run all test tests in parallel which are sitting in separate class files. This makes it easy to run our test in parallel without us doing any special configuration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With