daithanh-hua/java-unit-testing-standards icon
public
Published on 5/17/2025
Java Unit Testing Standards

Java Unit Testing (JUnit & Mockito) Rule

Rules

When writing Java unit tests:

  1. Frameworks: Use JUnit 5 and Mockito.
  2. Naming: Test method names should be descriptive, clearly stating what they test (e.g., givenX_whenY_thenZ or shouldReturnX_whenY).
  3. AAA Pattern: Structure tests using Arrange-Act-Assert.
  4. Mocking: Mock external dependencies (e.g., services, repositories) using Mockito.
  5. Assertions: Use specific assertions from org.junit.jupiter.api.Assertions (e.g., assertEquals, assertTrue, assertThrows).
  6. Coverage: Aim to test public methods of a class, covering different scenarios (happy path, edge cases, error conditions).
  7. Test Isolation: Each test should be independent and not rely on the state or outcome of other tests.