wrtte unit test in xunit to validate mac addresss in csharp

To write a unit test in xUnit to validate MAC addresses in C#, you can use the following code:

main.cs
using Xunit;
using System.Net.NetworkInformation;

public class MacAddressValidatorTest
{
    [Theory]
    [InlineData("00-81-73-E4-8C-AF", true)]
    [InlineData("00:81:73:E4:8C:AF", true)]
    [InlineData("00-81-73-E4-8C-AF-FA", false)]
    [InlineData("0081.73E4.8CAF", true)]
    [InlineData("0081.73E4.8CAF.FF", false)]
    [InlineData("0081.73E4.8CAF:00", false)]
    [InlineData("invalid", false)]
    public void IsMacAddress_ValidatesMacAddress(string macAddress, bool expectedResult)
    {
        var result = MacAddressValidator.IsMacAddress(macAddress);
        Assert.Equal(expectedResult, result);
    }
}

public static class MacAddressValidator
{
    public static bool IsMacAddress(string macAddress)
    {
        try
        {
            PhysicalAddress address = PhysicalAddress.Parse(macAddress);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
923 chars
36 lines

In this code, we have a unit test class named MacAddressValidatorTest. Inside this class, we have a single theory named IsMacAddress_ValidatesMacAddress which takes two parameters: a MAC address and the expected result of the validation.

The [InlineData] attribute is used to pass test data to the IsMacAddress_ValidatesMacAddress theory. We pass the MAC address and its expected validation result for each test case.

The MacAddressValidator class contains a single static method named IsMacAddress which takes a MAC address as a string and returns a boolean indicating whether the address is valid or not.

The PhysicalAddress.Parse method is used to parse the MAC address string and throw an exception if the address is not valid. If an exception is thrown, the IsMacAddress method returns false. Otherwise, it returns true.

Finally, the Assert.Equal method is used to compare the actual result of the validation with the expected result, and fail the test if they are not the same.

related categories

gistlibby LogSnag