JUnitとMockitoによる単体テスト
コンポーネントを分離してテストします
「JUnitとMockitoによる単体テスト」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Microservices & REST APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Unit Tests
A unit test verifies a single class in isolation, with its collaborators replaced by fakes.
- Fast — no Spring context, no database
- Focused — tests one piece of logic
- Reliable — no external dependencies
JUnit 5 Basics
Spring Boot uses JUnit 5 (Jupiter). A test is a method annotated with @Test.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void addsTwoNumbers() {
assertEquals(5, 2 + 3);
}
}Lifecycle Annotations
Use @BeforeEach to set up state before each test and @AfterEach to clean up.
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
void addsCorrectly() {
assertEquals(7, calculator.add(3, 4));
}AssertJ Fluent Assertions
Spring Boot bundles AssertJ for readable assertions with assertThat.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(result).isEqualTo(42);
assertThat(list).hasSize(3).contains("a");What is Mockito
Mockito creates mock objects — fake implementations of dependencies whose behavior you control.
This lets you test a class without its real collaborators (database, HTTP clients, etc.).
Creating Mocks
Annotate the test class with @ExtendWith(MockitoExtension.class). Use @Mock for dependencies and @InjectMocks for the class under test.
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
UserRepository repository;
@InjectMocks
UserService service;
}Stubbing with when/thenReturn
Define a mock's behavior with when(...).thenReturn(...).
@Test
void returnsUserById() {
User alice = new User("1", "Alice");
when(repository.findById("1"))
.thenReturn(Optional.of(alice));
User result = service.getById("1");
assertThat(result.getName()).isEqualTo("Alice");
}Throwing from a Mock
Use thenThrow to simulate error conditions.
when(repository.findById("99"))
.thenThrow(new RuntimeException("DB down"));
assertThrows(RuntimeException.class,
() -> service.getById("99"));Verifying Interactions
verify checks that a mock method was called with expected arguments.
@Test
void savesUser() {
service.create(new User("2", "Bob"));
verify(repository).save(any(User.class));
verify(repository, times(1)).save(any());
}Argument Matchers
Matchers like any(), eq(), and anyString() make stubs flexible.
when(repository.findByName(anyString()))
.thenReturn(List.of(new User("1", "Alice")));
verify(repository).deleteById(eq("1"));Capturing Arguments
ArgumentCaptor captures the value passed to a mock so you can assert on it.
ArgumentCaptor<User> captor =
ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().getName())
.isEqualTo("Bob");Quick Check
Test your understanding of Mockito.
Recap
You learned to write fast unit tests:
- JUnit 5 with
@Test,@BeforeEach - AssertJ
assertThatfor readable checks - Mockito
@Mock/@InjectMocks when/thenReturnto stub,verifyto confirm calls
よくある質問
「JUnitとMockitoによる単体テスト」レッスンは無料ですか?
はい。「JUnitとMockitoによる単体テスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。
「JUnitとMockitoによる単体テスト」で何を学びますか?
コンポーネントを分離してテストします ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Spring Boot 4 Microservices & REST APIsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSpring Boot 4 Microservices & REST APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「JUnitとMockitoによる単体テスト」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSpring Boot 4 Microservices & REST APIsレッスンでコードを書いて実行できますか?
はい。すべてのSpring Boot 4 Microservices & REST APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- JUnitとMockitoによる単体テスト
- MockMvcによるWeb層テスト
- @SpringBootTestによる統合テスト
- Testcontainersによる実際の依存関係のテスト