Catalog / JUnit Testing Cheatsheet
JUnit Testing Cheatsheet
A concise reference for writing effective unit tests in Java using JUnit. Covers annotations, assertions, test fixtures, and best practices for robust testing.
JUnit Fundamentals
Core Annotations
|
Marks a method as a test case. JUnit will execute this method when running tests. |
|
Specifies a method to be executed before each test method in the class. Used for setting up test fixtures. |
|
Specifies a method to be executed after each test method in the class. Used for tearing down test fixtures. |
|
Specifies a method to be executed once before any of the test methods in the class are executed. Must be static. |
|
Specifies a method to be executed once after all of the test methods in the class have been executed. Must be static. |
|
Marks a test method as disabled/ignored. The test will not be executed. |
Basic Assertions
|
Asserts that two values are equal. Can be used with various data types. |
|
Asserts that a condition is true. |
|
Asserts that a condition is false. |
|
Asserts that an object is null. |
|
Asserts that an object is not null. |
|
Asserts that two objects refer to the same object. |
|
Asserts that two objects do not refer to the same object. |
Exception Testing
|
Advanced Assertions & Features
Advanced Assertions (JUnit 5)
|
Asserts that all supplied executables do not throw exceptions. Useful for grouping multiple assertions.
|
|
Asserts that the execution of the supplied executable completes before the given timeout.
|
|
Similar to
|
Assumptions
Assumptions are conditions that must be true for a test to be meaningful. If an assumption fails, the test is aborted.
|
Parameterized Tests (JUnit 5)
Parameterized tests allow you to run the same test multiple times with different input values.
|
Test Fixtures and Suites
Test Fixtures
Test fixtures provide a fixed baseline for running tests. They ensure that the tests are executed in a consistent and repeatable environment.
|
Test Suites
Test suites allow you to group multiple test classes into a single execution unit.
|
Best Practices
Writing Effective Tests
|
Mocking
Mocking is a technique used to isolate the code under test from its dependencies. Mock objects simulate the behavior of real objects, allowing you to verify interactions and control the test environment.
|