Question

I have a custom assertion class that I'm currently unit testing.

public static class AssertionExtensions
{
    public static void ShouldHaveAttributeApplied<T>(this T obj, Type attributeType)
    {
        Assert.IsNotNull(Attribute.GetCustomAttribute(typeof(T), attributeType));
    }
}

The tests for this class are:

    [TestMethod]
    public void When_Called_For_Class_Validates_Pass_Correctly()
    {
        var obj = new FakeClass();
        obj.ShouldHaveAttributeApplied(typeof(FakeClassAttribute));
    }

    [TestMethod]
    public void When_Called_For_Class_Validates_Fail_Correctly()
    {
        var obj = new FakeClass();
        obj.ShouldHaveAttributeApplied(typeof(UnappliedFakeClassAttribute));
    }

The test When_Called_For_Class_Validates_Fail_Correctly fails as expected, but how do I mark this fail as a pass in the test suite?

This is using C# / MSTest.

Was it helpful?

Solution

Adding the ExpectedException attribute with the exception set to AssertionFailedException makes the test pass as intended.

Usage:

[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void When_Called_For_Class_Validates_Fail_Correctly()
{
    var obj = new FakeClass();
    obj.ShouldHaveAttributeApplied(typeof(UnappliedFakeClassAttribute));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top