Reader small image

You're reading from  Parallel Programming and Concurrency with C# 10 and .NET 6

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781803243672
Edition1st Edition
Right arrow
Author (1)
Alvin Ashcraft
Alvin Ashcraft
author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft

Right arrow

Chapter 12: Unit Testing Async, Concurrent, and Parallel Code

Unit testing asynchronous, concurrent, and parallel code can be a challenge for .NET developers. Fortunately, there are some steps you can take to help ease the difficulty. This chapter will provide some concrete advice and useful examples of how developers can unit test code that leverages multi-threaded constructs. These examples will illustrate how unit tests can still be reliable while covering code that performs multithreaded operations. In addition, we will explore a third-party tool that facilitates the creation of automated unit tests that monitor your code for potential memory leaks.

Creating unit tests for your .NET projects is important to maintain the health of your code base as it grows and evolves. When developers make changes to code that has unit test coverage, they can run the existing tests to feel confident that no existing functionality has been broken by the code changes. Visual Studio makes it simple...

Technical requirements

To follow along with the examples in this chapter, the following software is recommended for Windows developers:

  • Visual Studio 2022 version 17.2 or later
  • .NET 6
  • A JetBrains dotMemory Unit standalone console runner

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter12.

Let’s get started by examining how to write unit tests that cover async C# methods.

Unit testing asynchronous code

Unit testing asynchronous code requires the same approach as writing good asynchronous C# code. If you need a refresher on how to work with async methods, you can review Chapter 5.

When writing a unit test for an async method, you will use the await keyword to wait for the method to complete. This requires that your unit test method is async and returns Task. Just like other C# code, creating async void methods is not permitted. Let’s look at a very simple test method:

[Fact]
private async Task GetBookAsync_Returns_A_Book()
{
    // Arrange
    BookService bookService = new();
    var bookId = 123;
    // Act
    var book = await bookService.GetBookAsync(bookId);
    // Assert
    Assert.NotNull(book);
    Assert.Equal(bookId, book.Id);
}

This probably...

Unit testing concurrent code

In this section, we will adapt a sample from Chapter 9, to add unit test coverage. When your code uses async and await, adding reliable test coverage is very simple. At the end of the example, we will examine an alternative method of waiting to perform your assertions by using the SpinLock struct.

Let’s create an xUnit.net unit test project for the ConcurrentOrderQueue project and add several tests:

  1. Start by copying the ConcurrentOrderQueue project from Chapter 9. You can get the source code from the GitHub repository if you do not already have a copy of it: https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter09/ConcurrentOrderQueue.
  2. Open the ConcurrentOrderQueue solution in Visual Studio.
  3. Right-click the solution file in Solution Explorer and click on Add | New Project. Add an xUnit Unit Test project named ConcurrentOrderQueue.Tests. Make sure to add the new project...

Unit testing parallel code

Creating unit tests for code that use Parallel.Invoke, Parallel.For, Parallel.ForEach, and Parallel.ForEachAsync is relatively straightforward. While they can run processes in parallel when conditions are suitable, they run synchronously relative to the invoking code. Unless you wrap Parallel.ForEach in a Task.Run statement, the flow of code will not continue until all iterations of the loop have been completed.

The one caveat to consider when testing code that uses parallel loops is the type of exceptions to expect. If an exception is thrown within the body of one of these constructs, the surrounding code must catch AggregateException. The exception to this Exception rule is Parallel.ForEachAsync. Because it is called with async/await, you must handle Exception instead of AggregateException. Let’s create an example to illustrate these scenarios:

  1. Create a new Class Library project in Visual Studio named ParallelExample.
  2. Rename Class1...

Checking for memory leaks with unit tests

Memory leaks are by no means unique to multithreaded code, but they certainly can happen. The more code that is executing in your application, the more likely it is that some objects are going to leak. The company that makes the popular .NET tools, ReSharper and Rider, also makes a tool called dotMemory for analyzing memory leaks. While these tools are not free, JetBrains does offer its memory unit testing tool for free. It’s called dotMemory Unit.

In this section, we will create a dotMemory Unit test to check whether we are leaking one of our objects. You can run these dotMemory Unit tests for free with .NET on the command line by downloading the standalone test runner here: https://www.jetbrains.com/dotmemory/unit/.

Note

For more information about using the free tooling, you can read about it here: https://www.jetbrains.com/help/dotmemory-unit/Using_dotMemory_Unit_Standalone_Runner.html. JetBrains also has integration for...

Summary

In this chapter, we learned about some tools and techniques to unit test .NET projects that contain different multithreaded constructs. We started by discussing the best methods for testing C# code that employs async/await. This will be common in modern applications, and it is important to have a suite of automated unit tests covering your async code.

We also walked through some examples of unit tests that test methods that leverage parallel constructs and concurrent data structures. In the last section of the chapter, we learned about dotMemory Unit from JetBrains. This free unit testing tool adds the ability to detect objects leaked by methods under test. It is a powerful automation tool for synchronous and asynchronous .NET code.

This is the final chapter. Thanks for following along on this multithreading journey. Hopefully, you didn’t encounter any deadlocks or race conditions along the way. This book provided guidance for your path through the modern, multithreaded...

Questions

  1. What is the keyword used in .NET attributes that decorate an xUnit.net test method?
  2. What method can you use to add await to your code without locks?
  3. What type of exception should you expect in unit test assertions when the method under test contains a Parallel.ForEach loop?
  4. What type of exception should you expect in unit test assertions when the method under test contains a Parallel.ForEachAsync loop?
  5. How can you check that an object isn’t null in an xUnit.net assertion?
  6. What is the name of the window in Visual Studio where unit tests can be managed and run?
  7. What are the three most popular unit test frameworks for .NET?
  8. Which JetBrains products provide tooling to run dotMemory Unit tests?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Parallel Programming and Concurrency with C# 10 and .NET 6
Published in: Aug 2022Publisher: PacktISBN-13: 9781803243672
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft