

Ask HN: What is the unit in unit testing? - gamebit07

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!
======
tgpc
Choose units that have clear interfaces between each other.

Say you have (in this example, Java) classes A, B and C. A is public, B is
public, C is package local to B.

It might make sense to test A independently, possibly with a mock B.

Then look to see if B and C can be tested together - the package local
relationship suggests they may be the same unit.

There are no hard and fast rules, IMHO. If your tests are a world of pain,
consider breaking things down in different ways.

Checking for a 500 sounds like it might be an acceptance test. Only hit the
interface your program exposes for these!

As a worked example:

class PageGenerator { Page generate() throws ServerException { ... } }

class HttpProtocolHandler { HttpResponse handleRequest(HttpRequest req) {
myPageGenerator.generate(); } }

Unit test PageGenerator. Assert that it throws a ServerException on error.

Unit test HttpProtocolHandler. Assert that if a mock PageGenerator throws an
exception, the HttpResponse from handleRequest has status 500.

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.

Happy to help more if you would like.

------
logn
A class should do one thing and do it well. It should be just as long as it
needs to be.

A unit is not test for a 500 error, that usually an integration test, testing
end-to-end functionality.

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.

