ExpectedException Assert

前端 未结 5 1221
死守一世寂寞
死守一世寂寞 2021-02-08 05:25

I need to write a unit test for the next function and I saw I can use [ExpectedException]

this is the function to be tested.

public static T FailIfEnumIs         


        
5条回答
  •  星月不相逢
    2021-02-08 06:00

    ExpectedException just asserts that exception of specified type will be thrown by test method:

    [TestMethod] 
    [ExpectedException(typeof(ArgumentOutOfRangeException))]
    public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
    {
        // PREPARE
        // EXECUTE
        // NO ASSERT!!
    }
    

    If you want to assert other parameters of exception, then you should use try..catch in your test method:

    [TestMethod]     
    public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
    {
        // PREPARE
    
        try
        {
           // EXECUTE
           Assert.Fail()
        }
        catch(Exception exception)
        {        
            // ASSERT EXCEPTION DETAILS
        }
    }
    

    You can write your own method for asserting exception was thrown to avoid repeating same test code over and over again:

    public TException AssertCatch(Action action)
        where TException : Exception
    {
        try
        {
            action();
        }
        catch (TException exception)
        {
            return exception;
        }
    
        throw new AssertFailedException("Expected exception of type " + 
                                        typeof(TException) + " was not thrown");
    }
    

    Usage:

    var exception = AssertCatch(() => /* EXECUTE */);
    Assert.AreEqual("foo", exception.Message);
    

提交回复
热议问题