XUnit tests
scroll

XUnit and Exceptions With async Task

 

When a business object requires catching exceptions generated by wrong property values, XUnit tests aren't as easy to write.

Recently, I wrote XUnit tests for a business object that requires catching exceptions generated by wrong property values in synchronous and asynchronous calls. This post includes several examples. The full code is accessible on GitHub. Here, I will use the approach described in Richard Banks' post, Stop Using Assert.Throws in Your BDD Unit Tests.

Let's describe objects that will be used for demonstration. The Data сlass describes the simple object with one property that throws an exception on negative values:

public class Data
{
  private readonly object _lockObject = new object();

  private int _state;

  public int State
  {
    get { return _state; }
    set
    {
      lock (_lockObject)
      {
        if (value < 0)
          throw new ArgumentOutOfRangeException(
            nameof(State),
            "State should be positive");
        _state = value;
        // some inner changes
      }
    }
  }
}

Let's write a simple test that assigns positive values and doesn't throw an exception:

[Theory]
[InlineData(0)]
[InlineData(1)]
public void Data_ShouldAccept_NonNegativeValue(int state)
{
  Data data = null;
  var exception = Record.Exception(() =>
  {
    data = new Data();
    data.State = state;
  });
  data.Should().NotBeNull();
  exception.Should().BeNull();
}

All tests are executed successfully and the exception is not thrown!

Web Solutions

 

Now, let's consider the test that assigns negative state and throws an exception:

[Theory]
[InlineData(-1)]
public void Data_ShouldThrow_ExceptionOnNegativeValueAndReturnNullObject(int state)
{
  Data data = null;
  Action task = () =>
    {
      data = new Data
      {
        State = state
      };
    };
  var exception = Record.Exception(task);
  data.Should().BeNull();
  exception.Should().NotBeNull();
  exception.Message.Should().Be(ExceptionMessage);
}

As the Data class is designed to be thread-safe, we need tests that accesses  Data.State asynchronously.

Note that the used method Record.ExceptionAsync returns a value of type Task and marked as can be null. That is why the returned result is checked against a null value. Then, we check for the inner exception:

[Fact]
public void Data_ShouldNotThrow_ExceptionOnNonNegativeValueInAsync()
{
  var data = new Data();
  var task = Task.Run(() =>
        {
          for (var pos = 5; pos >= 0; pos--)
          {
            data.State = pos;
          }
        });
  var taskException = Record.ExceptionAsync(async () => await task);
  data.Should().NotBeNull();
  data.State.Should().Be(0);
  taskException.Should().NotBeNull();
  taskException.Result.Should().BeNull();
}

Further, the next test correctly catches the generated exception:

 
[Fact]
public void Data_ShouldThrow_ExceptionOnNegativeValueInAsync()
{
  var data = new Data();
  var task = Task.Run(() =>
        {
          for (var pos = 1; pos >= -2; pos--)
          {
            data.State = pos;
          }
        });
  var exception = Record.ExceptionAsync(async () => await task);
  data.Should().NotBeNull();
  data.State.Should().Be(0);
  exception.Should().NotBeNull();
  exception.Result.Should().NotBeNull();
  exception.Result.Message.Should().Be(ExceptionMessage);
}

The similar test could be written with two asynchronous tasks:

[Fact]
public void Data_ShouldThrow_ExceptionOnNegativeStateInTwoAsyncTasks()
{
  var data = new Data();
  var tasks = new Task[]
    {
      Task.Run(() =>
        {
          for (var pos = 0; pos < 10; pos++)
          {
            data.State += 1;
          }
        }), 
      Task.Run(() =>
        {
          for (var pos = 0; pos < 20; pos++)
          {
            data.State -= 1;
          }
        }), 
    };
  var exception = Record.ExceptionAsync(async () =>
        await Task.WhenAll(tasks));
  data.Should().NotBeNull();
  exception.Should().NotBeNull();
  exception.Result.Should().NotBeNull();
  exception.Result.Message.Should().Be(ExceptionMessage);
}

That's it! You've now created XUnit tests for a business object that requires catching exceptions generated by wrong property values in synchronous and asynchronous calls.

Illya Reznykov - Svitla Systems
by Illya Reznykov
CTO and Senior Cloud Architect
A seasoned and certified Cloud Architect with over 25 years of experience, Illya has a proven track record of transforming legacy applications through codebase review, refactoring, optimization, migration, and integrating new features. His hands-on experience with CI/CD pipelines, on-premises, and cloud deployments in AWS and Azure and supporting multiple environments further illustrates his versatility as a leader in the cloud domain.

Let's discuss your project

We look forward to learning more and consulting you about your product idea or helping you find the right solution for an existing project.

Thank you! We will contact very shortly.

Your message is received. Svitla's sales manager of your region will contact you to discuss how we could be helpful.