C4 - Lesson 5: Unit Testing With Java Flashcards
Unit Tests
A piece of code that verifies the one behavior of another piece of code.
- Each behavior your application performs should have its own unit test.
- Each unit test should verify one behavior.
- Let you know if you broke something.
Behaviour
A unit test can verify different behavioral aspects of the system under test, but most likely it will fall into one of the following two categories: state-based or interaction-based. Verifying that the system under test produces correct results, or that its resulting state is correct, is called state-based unit testing, while verifying that it properly invokes certain methods is called interaction-based unit testing.
Unit Testing Frameworks
solve some of these problems Only tests one scenario No boundary checking Throws an exception that would interrupt other tests Must be manually executed
Unit Test Tips:
Short - Simple unit tests that verify a single, concrete requirement.
Names - Clear names that are communicate the requirement they test.
Success and Failure - In addition to testing for expected results, test for failures and invalid states.
Speed - Tests should run quickly, because they should run often. Slow tests often indicate problem code.
Minimize Pre-conditions - Don’t overuse @BeforeEach to do things that are not relevant to every test. This makes your tests slower and obscures the requirements.
Thorough - Test all branching conditions.
Why mocks are important for unit tests?
Our goal is specifically to test the SecurityService class, and so you should avoid writing unit tests that rely on the behavior of the Repository or ImageService.
SecurityService so that your unit tests do not rely on the ImageService or SecurityRepository functioning correctly.
Remember, if the image service or repository are broken, this should not break your unit tests as they only test the Security Service.