Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
CommentServiceTest runs the real CommentService with three Mockito mocks for its repositories: no Spring, no database, five tests in a fraction of a second. An AI drafts it from a short prompt; we read each test, run it, and learn to read the red message when an expectation is wrong.
What you will learn
- Tell a one-class unit test from a whole-app @SpringBootTest
- Set up @Mock repositories and @InjectMocks for the real service
- Read an AI-drafted test as given, when, then, with an ArgumentCaptor
- Run one test class, then the whole suite, and read a failure message
Before you start
- Building a Feature With an AI Agent, End to End
- JUnit 5 basics
A unit test checks one class on its own. Here it's CommentService from the blog's comments feature. An AI writes the first draft from a short prompt; we read it, run it, and keep it when it's green.
The whole app, or one class
The project already has tests like CommentTest, marked @SpringBootTest: it starts the whole app, database and all, before its five tests run, and takes about nine seconds. The new CommentServiceTest uses @ExtendWith(MockitoExtension.class): one class with three mock repositories, no Spring and no database, and it takes about 0.3 seconds. Both are useful; a unit test is the fast one.
Mocks stand in for the repositories
Think of a rehearsal with stand-ins. Mockito makes one mock per @Mock field. @InjectMocks makes Mockito call new CommentService(...) with the three mocks in its constructor, so the service is the real one. Each mock only knows the lines we give it.
// a plain unit test: no Spring, no database - the repositories are Mockito mocks
@ExtendWith(MockitoExtension.class)
class CommentServiceTest {
@Mock
private CommentRepository commentRepository;
@Mock
private PostRepository postRepository;
@Mock
private AccountRepository accountRepository;
@InjectMocks
private CommentService commentService;
private final Account emma = new Account("Emma Clark", "[email protected]", "hash", Role.USER);
private final Post post = new Post("Hello from the database", "Community", "A short summary.",
LocalDate.of(2024, 6, 12), emma);
private final Comment emmasComment = new Comment("Nice post!", emma, post, LocalDateTime.of(2024, 6, 12, 18, 5));
The test makes its own data with plain new: Emma's account, her post and her comment.
A short prompt, a first draft
The prompt asks for plain JUnit 5 and Mockito, mocks for the three repositories, and the cases we care about: add saves the comment with its author and post, the author may delete, another user gets access denied, the admin may delete any comment, and an unknown id is not found. The AI drafts the class. Then we read it: does each test check what its name says?
The first test: given, when, then
@Test
void addSavesTheCommentWithItsAuthorAndPost() {
// given
given(postRepository.findById(1L)).willReturn(Optional.of(post));
given(accountRepository.findByEmail("[email protected]")).willReturn(Optional.of(emma));
given(commentRepository.save(any(Comment.class))).willAnswer(call -> call.getArgument(0));
// when
commentService.add(1L, " Thanks for this! ", "[email protected]");
// then
ArgumentCaptor<Comment> saved = ArgumentCaptor.forClass(Comment.class);
verify(commentRepository).save(saved.capture());
assertThat(saved.getValue().getText()).isEqualTo("Thanks for this!");
assertThat(saved.getValue().getAuthor()).isSameAs(emma);
assertThat(saved.getValue().getPost()).isSameAs(post);
}
Given tells each mock what to answer. When calls the real add, with spaces around the text. Then catches the comment handed to save with an ArgumentCaptor. The text must have lost its spaces, so the strip really happened, and the author and post must be the very same objects we gave (isSameAs).
The delete tests: who may?
@Test
void anotherUserGetsAccessDenied() {
given(commentRepository.findById(7L)).willReturn(Optional.of(emmasComment));
assertThatThrownBy(() -> commentService.delete(7L, login("[email protected]", "ROLE_USER")))
.isInstanceOf(AccessDeniedException.class);
verify(commentRepository, never()).delete(any());
}
@Test
void theAdminDeletesAnyComment() {
given(commentRepository.findById(7L)).willReturn(Optional.of(emmasComment));
commentService.delete(7L, login("[email protected]", "ROLE_ADMIN"));
verify(commentRepository).delete(emmasComment);
}
@Test
void anUnknownCommentIsNotFound() {
given(commentRepository.findById(99L)).willReturn(Optional.empty());
assertThatThrownBy(() -> commentService.delete(99L, login("[email protected]", "ROLE_ADMIN")))
.isInstanceOf(ResponseStatusException.class);
}
private Authentication login(String email, String role) {
return new UsernamePasswordAuthenticationToken(email, null, List.of(new SimpleGrantedAuthority(role)));
}
Each starts with the mock handing back Emma's comment, id 7. Noah gets an AccessDeniedException, and never() proves the repository's delete wasn't called at all. Chaand, the admin, gets the delete. An unknown id, 99, makes the mock return nothing and the service says not found. The small login helper builds an Authentication without starting Spring Security.
Run it: one class, then all
./mvnw test -Dtest=CommentServiceTest
./mvnw test
The first command runs only our class: 5 tests, 0 failures, 0 errors, build success in under ten seconds. The second runs every test in the project, the Spring tests like CommentTest and our unit test among them: 53 tests in total, all green.
When it fails, read the message
In a scratch copy, one expectation was changed to leave out the exclamation mark. The run says 5 tests, 1 failure, names addSavesTheCommentWithItsAuthorAndPost, shows expected "Thanks for this" but was "Thanks for this!", and points at line 68. The test was wrong, not the service. The message gives you the test, the line, what was expected and what came back, which is exactly what you need to decide which side to fix. The AI writes the draft; you still read it before you trust it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
The blog's Dockerfile runs mvnw package with -DskipTests=${SKIP_TESTS}, false by default, so every docker build runs all 53 tests and a red one means no image. --build-arg SKIP_TESTS=true cuts the package step from 41 to 23 seconds, which is only safe after CI has run the tests.
The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
One small ticket desk, three kinds of test: four plain unit tests in 20 ms, two @WebMvcTest slice tests in 4.4 s, one @SpringBootTest flow in 711 ms. Where each rule belongs, and what you should never test at all.
Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
Test TicketService.close on its own: a stub repository that answers findById, a mock notifier that records send, verify to check both calls, and a HashMap fake that really stores the closed ticket.
Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
Start only the layer you test. Three MockMvc tests for a ticket controller (200 with JSON, 404, a JSON list), the 'no qualifying bean' failure when the mock is missing, two @DataJpaTest tests on H2, and bean counts of 124, 80 and 224.
