The Importance of Setup and Teardown
Learn how to use shared code in tests.
When we run xUnit tests, each scenario is isolated from other scenarios, and the tests are typically stateless. However, sometimes different test scenarios have the same setup sequence. Likewise, sometimes test scenarios create artifacts that need to be cleaned up after every run or use unmanaged resources that have to be disposed of correctly. These aspects entail the setup and teardown logic.
The following playground demonstrates examples of the setup and teardown logic in xUnit:
namespace MainApp; public class FileLogger { public const string LogFileName = "log.txt"; public void WriteToLog(string? message) { if (string.IsNullOrWhiteSpace(message)) return; using StreamWriter writer = new(LogFileName, true); writer.WriteLine(message); } }
In this example, we test the FileLogger
class from the MainApp
project. The content of the FileLogger.cs
file containing this class is as follows:
namespace MainApp;public class FileLogger{public const string LogFileName = "log.txt";public void WriteToLog(string? message){if (string.IsNullOrWhiteSpace(message))return;using StreamWriter writer = new(LogFileName, true);writer.WriteLine(message);}}
Here, we use the WriteToLog()
method on line 7, which takes a nullable string as a parameter. If the string value is null, it means it’s empty or consists entirely of whitespace characters, such as spaces and tabs. This is defined by the IsNullOrWhiteSpace()
method on line 9. We then exit the earlier method. Otherwise, on line 13, we write the input value into a separate line in a file with the ...