A unit test is a small tests meant to test the correct working of a small unit of the whole system.
This is usually on the level of single functions which rank low in the overall abstraction hierarchy.
Such tests can be either black or white box tests
It is considered best practice to write unit tests functions which are non trivial.
The problem hence is defining what is non trivial.
While approaches like Test Driven Development advocate, that every function is non trivial,
opponents of this methodology point out, that functions that only use build in functionality like:
Pydef add(x, y): return x + y
are probably not worth the amount of overhead that writing a tests occurs.
Test the function if:
- The function is non-changing.
- The function is used in multiple contexts.
- Each iteration of the function is required to fulfill certain properties.
Don't test functions if:
- It is uncertain that the function will exist tomorrow.
- You don't know if and where the function will be used.
- The function is only composed of preexisting functions that were tested.
The reasons for testing always outweigh the reasons against testing.
Often unit tests can be grouped to reduce repetitive code.
Some testing frameworks offer this functionality out of the box like NUnit
:
Cs[Test] [TestCase(1, "1")] [TestCase(2, "2")] [TestCase(3, "Fizz")] // Further cases omitted for brevity public void FizzBuzz(int input, string expected) { Assert.AreEqual(expected, UnderTest.FizzBuzz(input)); }
Similar functionality can be achieved in all programming languages.
Pydef my_test(self): data = [(1, "1"), (3, "Fizz"), (5, "Buzz")] for inpt, expected in data: self.assertEqual(expected, fizz_buzz(inpt))