I’m told that granularity is good, up to a point. But we don’t want to go too far. When I do go too far, I’ve been told more times than I can count that I’m being rigid or pedantic or mindlessly following rules. I don’t think that’s true, but I don’t have enough experience to defend my preferences well.
So, I thought I’d ask *you*.
I want to (remain open to learning new ways, and also) get better at explaining why I like:
- Test names that describe a small characteristic of our system (typically called behavior). Like “a new account has a balance of zero” or “opens new accounts with a balance of zero”.
- Asserts that match the name of the test.
I think that the tinier the test, the more likely we are to quickly know what went wrong when it breaks. I also think that tests that describe real behavior or characteristics:
- are less likely to be stoopid tests—that is, not test for something we don’t want, like the ones I’ve seen that assert that for every new person, their name is Brian, and
- are useful in letting us know what we have done and what we haven’t, and
- help us find what broke, when they fail
What do you say? Should tests combine several asserts? Do we really need single-assert (single behavior, single characteristic) tests? And, are names important? How do we name tests?
One of the reasons for me coining the term “microtest” was precisely to aim at the notion of very tiny tests.
I do occasionally have a test that contains a single behavior but multiple assertions. “One behavior” really means “One path through one function”, not “one variable changed”. I sometimes argue that we should add these two more assertions to test the two more changes made by a single path through the function. It’s not “one test per line of code”, it’s “one test per path”. Anyway, the argument is not very significant, and I yield quite easily.
Most TDD beginners envision and enact tests that test far too much in one test. If we’re to err in the size of our microtests, the error of making them too small is far less dangerous than the error of making them too big. If you can see how to write a smaller microtest, go ahead and do it.