Is Assert.Fail() considered bad practice?

前端 未结 14 1139
面向向阳花
面向向阳花 2021-01-31 07:20

I use Assert.Fail a lot when doing TDD. I\'m usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where

14条回答
  •  孤街浪徒
    2021-01-31 07:28

    This is the pattern that I use when writting a test for code that I want to throw an exception by design:

    [TestMethod]
    public void TestForException()
    {
        Exception _Exception = null;
    
        try
        {
            //Code that I expect to throw the exception.
            MyClass _MyClass = null;
            _MyClass.SomeMethod();
            //Code that I expect to throw the exception.
        }
        catch(Exception _ThrownException)
        {   
            _Exception = _ThrownException
        }
        finally
        {
            Assert.IsNotNull(_Exception);
            //Replace NullReferenceException with expected exception.
            Assert.IsInstanceOfType(_Exception, typeof(NullReferenceException));
        }
    }
    

    IMHO this is a better way of testing for exceptions over using Assert.Fail(). The reason for this is that not only do I test for an exception being thrown at all but I also test for the exception type. I realise that this is similar to the answer from Matt Howells but IMHO using the finally block is more robust.

    Obviously it would still be possible to include other Assert methods to test the exceptions input string etc. I would be grateful for your comments and views on my pattern.

提交回复
热议问题