Writing Operating Specific Test Assertion For xUnit In C# & .NET
[C#, .NET, Testing, xUnit]
As I have mentioned before, my development environment is as follows:
- MacBook Pro, running macOS Sequoia
- My primary development environment is JetBrains Rider
- Virtualized Windows 11 Environment on Parallels Desktop Pro
- The development environment is Visual Studio 2022 and Visual Studio Code
Recently, I was writing tests for a component that behaved differently on Windows.
The test itself is as follows:
public void Config_Is_Constructed_Correctly_With_EventLog_Issues()
{
var settings = ElasticSearchSettings.GetSettings(TestConstants.ConnectionString, "Application", "1.0", true);
var config = LoggerBuilder.GetElasticSearchLogger(settings, _output);
config.Should().NotBeNull();
// Check whether log message is written to the Windows Event log
_output.Output.Should().Contain("Application is not registered as an event source");
}
The code in question is this:
// Check whether log message is written to the Windows Event log
_output.Output.Should().Contain("Application is not registered as an event source");
This code, obviously, only works on Windows. There is no EventLog on macOS and Linux.
This test would therefore pass on Windows but fail on macOS.
How to go about fixing this?
I ended up checking the platform just before running the assertion, using the IsOSPlatform like so:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
_output.Output.Should().Contain("Application is not registered as an event source");
The assertion, written with AwesomeAssertions, now runs only on Windows.
Happy hacking!