Java JUnit Test Generator (Spring Boot)
Generate comprehensive JUnit test cases for Java code following testing best practices with JUnit and Mockito.
Instructions
When generating Java tests for the given code, follow these steps:
1. Understand the Code
Read through the provided Java code to understand its functionality, including:
Classes and their responsibilitiesMethods and their interactionsDependencies and external systemsBusiness logic and validation rules2. Identify Test Cases
Determine the key functionalities and scenarios that need testing:
**Normal cases**: Valid inputs and expected flows**Edge cases**: Boundary conditions, empty collections, null inputs, min/max values**Error cases**: Invalid inputs, exceptions, constraint violations**Integration points**: Database access, external API calls, file operations3. Use JUnit Framework
Write tests using the JUnit framework (JUnit 5/Jupiter preferred):
Use `@Test` annotation for test methodsUse `@BeforeEach` for test setupUse `@AfterEach` for cleanupUse `@ParameterizedTest` for testing multiple scenariosUse `@DisplayName` for readable test descriptions4. Structure Tests Properly
Organize tests following these conventions:
Test class name: `{ClassName}Test` (e.g., `MovieServiceTest`)Test method naming: `should{ExpectedBehavior}_when{StateOrCondition}` (e.g., `shouldReturnMovie_whenValidIdProvided`)Group related tests using `@Nested` classesFollow Arrange-Act-Assert (AAA) pattern in each test5. Use Assertions Effectively
Verify expected outcomes with appropriate assertions:
`assertEquals()` for value comparison`assertTrue()` / `assertFalse()` for boolean conditions`assertNotNull()` / `assertNull()` for presence checks`assertThrows()` for exception testing`assertAll()` for multiple assertionsAssertJ or Hamcrest for fluent assertions (optional)6. Apply Mocking for Dependencies
Use Mockito to isolate the unit under test:
Use `@Mock` annotation for mock dependenciesUse `@InjectMocks` for the class under testUse `@ExtendWith(MockitoExtension.class)` to enable MockitoImport mocked classes properly with import statementsConfigure mock behavior with `when().thenReturn()`Verify interactions with `verify()`Use `@Spy` for partial mocking when needed7. Follow Spring Boot Testing Best Practices
For Spring Boot applications:
Use `@SpringBootTest` for integration testsUse `@WebMvcTest` for controller testsUse `@DataJpaTest` for repository testsUse `@MockBean` for Spring context mocksTest configuration with `@TestConfiguration`Example Test Structure
```java
@ExtendWith(MockitoExtension.class)
@DisplayName("MovieService Tests")
class MovieServiceTest {
@Mock
private MovieRepository movieRepository;
@InjectMocks
private MovieService movieService;
@Nested
@DisplayName("findById Tests")
class FindByIdTests {
@Test
@DisplayName("should return movie when valid ID provided")
void shouldReturnMovie_whenValidIdProvided() {
// Arrange
Long movieId = 1L;
Movie expectedMovie = new Movie(movieId, "The Matrix");
when(movieRepository.findById(movieId)).thenReturn(Optional.of(expectedMovie));
// Act
Movie actualMovie = movieService.findById(movieId);
// Assert
assertNotNull(actualMovie);
assertEquals(expectedMovie.getId(), actualMovie.getId());
assertEquals(expectedMovie.getTitle(), actualMovie.getTitle());
}
@Test
@DisplayName("should throw exception when movie not found")
void shouldThrowException_whenMovieNotFound() {
// Arrange
Long movieId = 999L;
when(movieRepository.findById(movieId)).thenReturn(Optional.empty());
// Act & Assert
assertThrows(MovieNotFoundException.class, () -> movieService.findById(movieId));
}
}
}
```
Coverage Goals
Aim for:
80%+ code coverage for business logic100% coverage for critical pathsAll public methods testedAll exception scenarios coveredConstraints
Do not test private methods directly (test through public methods)Avoid testing framework code (e.g., Spring annotations)Keep tests independent and idempotentEnsure tests run quickly (mock slow dependencies)Clean up resources in @AfterEach when needed