If you have questions click here for FAQs
For further reading click here for internet linksclick here
Definition
The definition of a unit test here is not the same as the definition in Wikipedia: the definition in Wikipedia covers both Interaction Tests and Unit Tests in the language used in this policy.
A unit test is a test for the smallest possible piece of code. Typically it will test a single method on a component If the code under test interacts with anything other than primitives or value objects it is NOT a unit test. If the code is a method then it can have a side effect of modifying internal valuse of the object and still be a unit test, although this is discouraged. See Avoid mutable state)
It is common to ‘blur’ the definition of unit test and include tests that test much more. This is to be avoided if possible. A test that isn’t a unit test as per this definition is of much less value to us: it is probably an interaction test or a whole system test
Things that cannot be unit tested with this definition
- Any method with a sideeffect (for example but not limited to)
- As a project you might decide that methods that produce log messages are acceptable. This is discouraged but acceptable
- Any method that modifies a metric
- Any method that writes to, or reads from a connection
- Any method that modifies one of the parameters that are passed to it
- Any method with a listener
- Any method that calls a method (something other than a simple getter or setter) on another object
It is entirely possible that most of the methods in your current code base cannot be unit tested. This is a sign that they do too much and should be refactored using the boy scout rule
Problems
It is hard to write code that can be unit tested: it requires practice and training. It is much easier to write code that cannot be unit tested. As professional software developers we should accept that this is harder, in exchange for the benefits:
- increased composability
- increased readability
- increased maintainability
Self checks
- If you have problems writing code that can be unit tested by this definition, request training
- If you have trouble writing unit tests that are short and simple, request training
- If you don’t find the unit tests give you value, request training
- If you are spending too long writing unit tests, request training