Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Some recent conversations I've had lead me to believe that not everyone is on the same page when it comes to unit tests, so I thought I'd go back to basics.
- Follow the three As principle: Arrange, Act, and Assert. Anyone should be able to glance at a unit test and immediately see what it's trying to demonstrate. I believe having the only blank lines in a unit test present between the three sections makes for easy reading.
- Unit tests should only test one thing: ninety-nine point nine percent of the time, the 'act' portion of a test will be a single line.
- Unit tests should only prove one thing: having more than a few Assert statements is an indication that the test is too broad.
For clarification, here are two versions of the same test. It's easy to see which is written correctly.
[Test]
public void testPop()
{
Stack s = new Stack();
s.Push(new object());
s.Pop();
Assert.AreEqual(0, s.Count);
}
[Test]
public void StackIsEmptyAfterPushingOneElementAndThenPopping()
{
Stack s = new Stack();
s.Push(new object());
s.Pop();
Assert.AreEqual(0, s.Count);
}