December 28, 2009

Contract Tests in JUnit 4

As part of his talk on integration tests J.B. Rainsberger talked about how contract tests can be used to test the interaction between classes when using a mockist approach to developer testing. He wondered aloud if it would be possible to write these kinds of tests using abstract classes and JUnit 4. The answer is yes, with some caveats, as I demonstrate in the screencast below. Enjoy!

EDIT: If the embedded screencast below doesn't work for you, try this link.

It not only runs changed tests, but selects an optimized subset of tests to run based on what you've changed (a feature not particularly apparent in a simple example like this). It's available with both a free and commercial license.

Using JUnit theories for something like this seems to me like it would violate the Open-Closed Principle, because in order to test a new type of list, youd have to go into the test and change it to include the new type.

Is there a way to use theories for this that doesnt suffer from that problem?

(I haven't watched Rainsberger's presentation yet, so maybe this question is addressed in there. Apologies if it is.)

The problem with making test classes inherit from one another is that you're limited by single inheritance. Say you've got a FileRepository class and a ReadableRepository interface, and you've written test classes for both. A ReadableFileRepository extends FileRepository and implements ReadableRepository. Is there a simple way to write a test class containing ReadableFileRepository specific tests, which also runs the test cases for FileRepository and ReadableRepository?