Basically I have two main questions:
- What exactly should you unit test?
- How do you do it?
The problem is I have several applications that rely in a database connection and/or are communication applications, which mean most of the test cases are integration tests (or so I think).
Most classes are fairly simple by themselves, but the ones that implement the communication protocol, which are the ones that would be useful to automate the testing, can seem to fit well into the “unit test” model.
Another example. I developed I pipe structure with multithreaded support for a consumer/producer pattern. When a thread reads the pipe and finds it empty it blocks until a writer writes into the pipe. Should I use unit tests to test that class?
How do you decide what to unit test?
Edit: I mean writing unit tests for automated unit testing.
You Unit tests units of your code. The real question is what exactly makes up a unit?
In an object oriented environment a unit is a class. A class because behaviours of an object vary with the state of the object, so testing a method in isolation will not yeild the most complete results.
First you need to identify the invariants of the class. That is, the things that will always be true for all instances ofthe class. E.g. in a Fraction class an invariant may be denominator != 0.
Next you need to identify the contracts of each method, that is, the pre and post conditions of the methods.
Then you write tests for each condition that may arise. So for a single class you may end up with many test methods to test the various conditions that each method could encounter. At each test you ensure that the invariants of the class holds and the contract of the method is never broken.
In some cases like the example that you provided it may be necessary to create other objects in the environment in order to test the conditions of your class. In those instances you may use mock objects.