共用方式為


Tests should explain something

I sometimes see unit tests which are downright confusingly opaque. Being a unit test, they are testing some smallish piece of code. Unfortunately by the time I finish reading the test I am none the wiser for what the importance of the code in question is, and what role it is meant to play in the larger system.

When I see a test like this, I feel like there has probably been a failure somewhere, for few possible reasons.
-It’s hard to code review the test.
-It’s hard to understand if the test failed in a way which matters.
-It’s possibly a brittle test which is closely tied to the implementation being tested and requires a lot of churn maintenance alongside its constantly churning implementation.

I feel like the underlying cause of all this is that the person writing the test hasn’t really asked themselves the question ‘why is it important that this test be written, and pass?’

The problem frequently shows itself in the name of the test, and the assertion section of the test.

public void TestNotifyCondition()
{
    obj = /* setup object */;
    Assert.Equal(true, obj.notifyCondition(true));
}

If you see this fail, will you instantly understand what you did wrong? Will you understand why someone asserts the return value is true? And how will you answer the question, 'Is it failing because I made a silly mistake, or because my intended design change to how this code works was a bad one?’

If implementation says what your system does, tests should say why it does it that way.