Writing A macOS-only method-level attribute for xUnit in C# & .NET
[C#, .NET, xUnit]
Yesterday’s post, “Writing A Windows-only method-level attribute for xUnit in C# & .NET”, looked at how to write an attribute for the xUnit test framework to mark a test as only to be run if the platform it is running under is Windows.
In this post, we will do the same for macOS.
We will leverage the same technique as before and use the OperatingSystem class to determine the current operating system.
The complete attribute will look like this:
using Xunit;
namespace Rad.xUnit.Extensions;
/// <summary>
/// Marks a test as only runnable in macOS
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class MacOSOnlyFactAttribute : FactAttribute
{
public MacOSOnlyFactAttribute()
{
if (!OperatingSystem.IsMacOS())
{
Skip = "This is a macOS Only Test";
}
}
}
You use it like this:
[MacOSOnlyFactAttribute]
public void Config_Is_Constructed_Correctly_With_EventLog_On_macOS_Issues()
{
//
// Test code here
//
}
If we run this test on macOS:

It runs successfully.
But if we run it on Windows:

We can see that it was skipped.
TLDR
We can use an xUnit attribute to designate tests as platform-specific (macOS).
The code is in my GitHub.
Happy hacking!