Mar 14, 2009

Unit Tests and CRC Cards

These days I was reading some old papers on the web. I found one about CRC cards (Class Responsibilities Collaborations) and I start thinking that Unit Tests should have some relationship with that. If you take a first look at CRC Cards, they define or document the specific responsibilities for a class and also its collaborators.



So, we can define all the collaborators in our Unit Tests and then implement them with mocks as usual. But what I really like was the idea of using a Unit Test to document responsibilities, so we only should have tests with names revealing responsibilities.



This is not new, but for some reason, at least in my experience, the most test cases I have seen declare a long list of test of methods. If the class under test has 3 getters you'll find at least 3 test cases in the way testGetXXXX(). That is not good. In my opinion Setters and Getters shouldn't be tested, even you shouldn't write them, but this is another topic.

Let's get back to CRC Cards. If you start thinking your tests as CRC Cards you can have a great benefit because when someone needs to modify a class, following TDD, he needs to modify the test to reflect the change and then start to write code. If that change affects a current responsibility you should modify all the tests that document it. If you need to add more responsibility to your class you will create one o more tests to document it. Also it's effective to detect bad designs, if you can't establish a responsibility to test a method maybe you need to review your design.


References:
http://c2.com/doc/oopsla89/paper.html#cards