Is Assert.Fail() considered bad practice?

前端 未结 14 1163
面向向阳花
面向向阳花 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:38

    Beware Assert.Fail and its corrupting influence to make developers write silly or broken tests. For example:

    [TestMethod]
    public void TestWork()
    {
        try {
            Work();
        }
        catch {
            Assert.Fail();
        }
    }
    

    This is silly, because the try-catch is redundant. A test fails if it throws an exception.

    Also

    [TestMethod]
    public void TestDivide()
    {
        try {
            Divide(5,0);
            Assert.Fail();
        } catch { }
    }
    

    This is broken, the test will always pass whatever the outcome of the Divide function. Again, a test fails if and only if it throws an exception.

提交回复
热议问题