I have been reading a log about testing these days, and luckily have been writing as well. One thing that became clear to me was, testing was good, but there were many school of thoughts. Coming from python background, there was nose, unittest, mock, py.test etc. Each school thinks they are right.
There is however an ambiguity on how we actually define unit in a unit test?<p>How do you define a unit? Is it the assertion that a response is 500. or is unit all assertions inside a test class. In that case how long should a class be? aprox lines of code?<p>It will be great if people can share their opinion/experience about it.
Appreciate your reading it, thanks!
Choose units that have clear interfaces between each other.<p>Say you have (in this example, Java) classes A, B and C. A is public, B is public, C is package local to B.<p>It might make sense to test A independently, possibly with a mock B.<p>Then look to see if B and C can be tested together - the package local relationship suggests they may be the same unit.<p>There are no hard and fast rules, IMHO. If your tests are a world of pain, consider breaking things down in different ways.<p>Checking for a 500 sounds like it might be an acceptance test. Only hit the interface your program exposes for these!<p>As a worked example:<p>class PageGenerator {
Page generate() throws ServerException {
...
}
}<p>class HttpProtocolHandler {
HttpResponse handleRequest(HttpRequest req) {
myPageGenerator.generate();
}
}<p>Unit test PageGenerator. Assert that it throws a ServerException on error.<p>Unit test HttpProtocolHandler. Assert that if a mock PageGenerator throws an exception, the HttpResponse from handleRequest has status 500.<p>Acceptance test both together. Start the web server and make an actual HTTP request you know will fail. Assert that the response code is 500.<p>Happy to help more if you would like.
A class should do one thing and do it well. It should be just as long as it needs to be.<p>A unit is not test for a 500 error, that usually an integration test, testing end-to-end functionality.<p>A unit can be as small as a single method. In Java, generally only public methods are tested. Units can be bigger, but you should be attempting to test the smallest unit of functionality you can. So start with testing a method and if that's not possible go higher.