DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Setup Cypress Tests in Azure DevOps Pipeline
  • Exploring Cloud-Based Testing With the Elastic Execution Grid
  • Integrating Selenium With Amazon S3 for Test Artifact Management
  • Software Specs 2.0: An Elaborate Example

Trending

  • MCP Client Agent: Architecture and Implementation
  • How to Achieve SOC 2 Compliance in AWS Cloud Environments
  • How to Marry MDC With Spring Integration
  • TIOBE Programming Index News June 2025: SQL Falls to Record Low Popularity
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. XUnit and Exceptions With async Task

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.

By 
Illya Reznykov user avatar
Illya Reznykov
·
Feb. 11, 17 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
19.2K Views

Join the DZone community and get the full member experience.

Join For Free

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!

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.

Task (computing) Testing

Published at DZone with permission of Illya Reznykov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Setup Cypress Tests in Azure DevOps Pipeline
  • Exploring Cloud-Based Testing With the Elastic Execution Grid
  • Integrating Selenium With Amazon S3 for Test Artifact Management
  • Software Specs 2.0: An Elaborate Example

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: