Challenge: Adding an Automated Test
Explore how to write automated tests with xUnit for a string-processing method in .NET. Understand how to handle different input cases including null, whitespace, and multi-word strings while adhering to best testing practices and avoiding code repetition.
We'll cover the following...
In the following setup, we have a class called TextProcessor in the MainApp project. This class has the CountNotWhitespaceCharacters() method, which accepts a nullable string as an input parameter and returns the count of all non-whitespace characters in it. We need to write automated test scenarios for this method covering the following conditions:
The empty string returns zero.
The null input returns zero.
The whitespace returns zero.
A tab character returns zero.
A string with no spaces, special characters, or digits returns the value equivalent to its length.
A string with two words separated by a space returns the total number of letters.
A string with three words separated by spaces, a leading whitespace, and a trailing tab character returns the total number of letters.
All the necessary code can be added to the TextProcessorTests.cs file. While writing these test scenarios, we must adhere to the best practices. There should be no unnecessary code repetition.
namespace MainApp;
public class TextProcessor
{
public int CountNotWhitespaceCharacters(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return 0;
int count = 0;
foreach (var character in text.Trim())
{
if (char.IsWhiteSpace(character))
continue;
count++;
}
return count;
}
}