Unit Testing – Single or Multiple Files for Testing a Single Class?

tddtestingunit testing

In researching unit testing best practices to help put together guidelines for my organization, I've run into the question of whether it is better or useful to separate test fixtures (test classes) or to keep all tests for a single class in one file.

Fwiw, I am referring to "unit tests" in the pure sense that they are white-box tests targeting a single class, one assertion per test, all dependencies mocked, etc.

An example scenario is a class (call it Document) that has two methods: CheckIn and CheckOut. Each method implements various rules, etc. that control their behavior. Following the one-assertion-per-test rule, I will have multiple tests for each method. I can either place all of the tests in a single DocumentTests class with names like CheckInShouldThrowExceptionWhenUserIsUnauthorized and CheckOutShouldThrowExceptionWhenUserIsUnauthorized.

Or, I could have two separate test classes: CheckInShould and CheckOutShould. In this case, my test names would be shortened but they'd be organized so all tests for a specific behavior (method) are together.

I'm sure there are pro's and con's to either approach and am wondering if anyone has gone the route with multiple files and, if so, why? Or, if you've opted for the single file approach, why do you feel it is better?

Best Answer

It's rare, but sometimes it makes sense to have multiple test classes for a given class under test. Typically I would do this when different setups are required, and shared across a subset of the tests.