Why do we prefer Unit tests to other tests

Answer 1-Better Code

The primary responsibility of unit tests is to force us to change the design of our code for the better. By requiring that we write unit tests

Answer 2-Better test reporting and faster defect detection

The nature of a unit test is that it is typically only coupled to a very tiny bit of code. If we imagine a body of code with 1,000 unit tests. If an error is introduced only a handful of unit tests will be impacted. They are like laser beams tightly focused on a simple piece of code and tell us if we have broken that bit of it.

If we compare this with an acceptance test in which the whole system is instantiated and a test run against the entire edifice… if there is a single error it might break every single test and the error reporting might well be ‘server code 500: there is a problem somewhere in your system’

What is the expected ratio of Unit tests to other tests

The ratio between the major types of tests is a measure of the programing teams’s skill at writing code, and a direct measure of the quality of the code. The short answer is that we expect more unit tests than all the other tests put together, and the more (meaningful and valuable) unit tests the better.

How many unit tests should I expect to write for a method

At least one: the happy path. Probably one for every Equivalence Class

What are the easiest things to be unit tested?

Almost anything else requires us to write a test higher up in our test pyramid than a unit test. It is because unit tests encourage us to write pure functions (even when programming in an object orientated way) that they force the code base to be better. Pure functions remove a whole axis of complexity: They mean that we do not have to consider the history of the code undertest

How big should be a unit test be

This is of course langauge dependant. In many ways we can measure the quality of the language by how short the unit tests can be, and how readable they can be.

In Java or C# or Scala, many unit tests should be one to three lines long:

If your methods are difficult to test in this way it is a sign that they are too complicated and need to be refactored. If you don’t know how to do this, or don’t understand the value of doing this, request training.