0Pricing
Spring Boot 4 Complete Guide · 강의

JUnit 및 Mockito를 활용한 단위 테스트

JUnit 5와 Mockito를 사용해 의존성을 모의 처리하면서 서비스 계층 구성 요소를 위한 효과적인 단위 테스트를 작성합니다.

JUnit 및 Mockito를 활용한 단위 테스트은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Welcome to Unit Testing!

In this lesson, you'll learn to write effective unit tests for your Spring Boot applications, specifically focusing on the service layer.

Unit tests are crucial for ensuring your code works as expected and catching bugs early in development. We'll use JUnit 5 and Mockito.

What is Unit Testing?

Unit testing means testing the smallest possible piece of code, called a 'unit', in isolation. For Java, a unit is typically a single method or class.

  • Isolation: Tests run independently, without external dependencies.
  • Speed: They execute very quickly, allowing frequent runs.
  • Early Detection: Catch bugs before they grow into bigger problems.

Introducing JUnit 5

JUnit 5 is the most popular testing framework for Java. It provides annotations and assertions to help you write structured and readable tests.

Let's see a basic test class structure. Notice the @Test annotation marks a method as a test case.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class SimpleCalculator {
  int add(int a, int b) {
    return a + b;
  }
}

// This is a JUnit 5 test class
class SimpleCalculatorTest {

  @Test
  void testAddition() {
    SimpleCalculator calc = new SimpleCalculator();
    int result = calc.add(2, 3);
    // An 'assertion' checks if the result is correct
    assertEquals(5, result, "2 + 3 should be 5");
    System.out.println("Addition test passed!");
  }

  public static void main(String[] args) {
    // In a real project, JUnit runs tests automatically.
    // Here, we simulate a call for demonstration.
    System.out.println("--- Simulating JUnit Test ---");
    new SimpleCalculatorTest().testAddition();
    System.out.println("--- Simulation Complete ---");
  }
}

Focusing on the Service Layer

In Spring Boot, the service layer usually contains your application's business logic. It orchestrates operations, often depending on data repositories.

Unit testing services is ideal because they:

  • Hold core logic.
  • Are typically plain Java classes.
  • Can be easily isolated from external systems (like databases).

The Challenge: Dependencies

Services often depend on other components, like a UserRepository to fetch user data. If we unit test a service, we don't want to hit a real database.

This is where mocking comes in! We need to simulate these dependencies to ensure our test is truly 'unit' (isolated).

Introducing Mockito for Mocking

Mockito is a popular mocking framework for Java. It lets you create 'mock' objects that simulate the behavior of real objects.

Instead of a real UserRepository talking to a database, we'll tell a Mockito-created mock repository exactly what to return when certain methods are called.

Setting Up Mocks with Annotations

Mockito provides handy annotations to simplify creating and injecting mocks:

  • @Mock: Creates a mock object for the specified type.
  • @InjectMocks: Creates an instance of the class under test and injects the @Mock objects into it.
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;

// Simple dependent class (e.g., a repository)
class DataRepository {
  String findDataById(String id) {
    throw new UnsupportedOperationException("Not implemented for real use!");
  }
}

// Our service class under test
class MyService {
  private final DataRepository repository;

  MyService(DataRepository repository) {
    this.repository = repository;
  }

  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
}

class MyServiceTestSetup {

  @Mock
  DataRepository mockRepository; // Mock of DataRepository

  @InjectMocks
  MyService myService; // Service where mocks are injected

  MyServiceTestSetup() {
    // This initializes the mocks
    MockitoAnnotations.openMocks(this);
    System.out.println("Mocks initialized for MyServiceTest!");
    System.out.println("mockRepository is a Mockito mock: " + (mockRepository != null));
    System.out.println("myService has mock injected: " + (myService != null));
  }

  public static void main(String[] args) {
    System.out.println("--- Setting Up Mocks Demo ---");
    new MyServiceTestSetup();
    System.out.println("--- Demo Complete ---");
  }
}

Defining Mock Behavior: when().thenReturn()

Once you have a mock, you need to tell it how to behave. Use Mockito.when().thenReturn() to define what a mock method should return for specific inputs.

This allows your service to run its logic using the fake data provided by the mock, without needing a real database or external service.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;

// Re-using classes from previous example
class DataRepository {
  String findDataById(String id) {
    return "Real Data for " + id;
  }
}

class MyService {
  private final DataRepository repository;
  MyService(DataRepository repository) {
    this.repository = repository;
  }
  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
}

class MyServiceTestBehavior {

  @Mock
  DataRepository mockRepository;

  @InjectMocks
  MyService myService;

  MyServiceTestBehavior() {
    MockitoAnnotations.openMocks(this);
  }

  @Test
  void testProcessDataWithMock() {
    // 1. Define mock behavior: when findDataById("123") is called,
    //    return "Mocked Data".
    when(mockRepository.findDataById("123")).thenReturn("Mocked Data");

    // 2. Call the service method
    String result = myService.processData("123");

    // 3. Assert the result
    assertEquals("Processed: Mocked Data", result);
    System.out.println("Test passed! Result: " + result);
  }

  public static void main(String[] args) {
    System.out.println("--- Mock Behavior Demo ---");
    MyServiceTestBehavior test = new MyServiceTestBehavior();
    test.testProcessDataWithMock();
    System.out.println("--- Demo Complete ---");
  }
}

Verifying Interactions with verify()

Sometimes, you don't just care about the return value, but also whether a specific method on a mock was called, and with what arguments.

Mockito's verify() method lets you assert that interactions with your mocks happened as expected. This is great for checking side effects.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

// Re-using classes from previous example
class DataRepository {
  String findDataById(String id) {
    return "Real Data for " + id;
  }
}

class MyService {
  private final DataRepository repository;
  MyService(DataRepository repository) {
    this.repository = repository;
  }
  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
  void saveData(String id, String data) {
    // Imagine this saves to DB via repository
    repository.findDataById(id); // Example interaction
    System.out.println("Saving data via mock...");
  }
}

class MyServiceTestVerification {

  @Mock
  DataRepository mockRepository;

  @InjectMocks
  MyService myService;

  MyServiceTestVerification() {
    MockitoAnnotations.openMocks(this);
  }

  @Test
  void testProcessDataAndVerify() {
    // Define mock behavior
    when(mockRepository.findDataById("456")).thenReturn("Verify Data");

    // Call the service method
    String result = myService.processData("456");

    // Assert the result
    assertEquals("Processed: Verify Data", result);

    // Verify that findDataById was called exactly once with "456"
    verify(mockRepository, times(1)).findDataById("456");
    System.out.println("Test passed! Method interaction verified.");
  }

  public static void main(String[] args) {
    System.out.println("--- Mock Verification Demo ---");
    MyServiceTestVerification test = new MyServiceTestVerification();
    test.testProcessDataAndVerify();
    System.out.println("--- Demo Complete ---");
  }
}

Quick Check: Mockito's Role

When unit testing a Spring service that depends on a repository, what is the primary role of Mockito?

Recap: Unit Testing Mastery

Congratulations! You've taken your first steps into effective unit testing with Spring Boot.

  • Unit tests verify small code units in isolation.
  • JUnit 5 is our testing framework, using @Test.
  • We focus on the service layer for business logic.
  • Mockito helps us create mock objects for dependencies.
  • Use @Mock, @InjectMocks to set up tests.
  • Define mock behavior with when().thenReturn().
  • Verify interactions with verify().

Keep practicing, and your code will be more robust than ever!

자주 묻는 질문

“JUnit 및 Mockito를 활용한 단위 테스트” 강의는 무료인가요?

네 — “JUnit 및 Mockito를 활용한 단위 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

“JUnit 및 Mockito를 활용한 단위 테스트”에서 뭘 배우나요?

JUnit 5와 Mockito를 사용해 의존성을 모의 처리하면서 서비스 계층 구성 요소를 위한 효과적인 단위 테스트를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“JUnit 및 Mockito를 활용한 단위 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. JUnit 및 Mockito를 활용한 단위 테스트
  2. Spring Boot 통합 테스트
  3. 슬라이스 테스트 및 TestContainers
  4. MockMvc로 웹 컨트롤러 테스트
← Spring Boot 4 Complete Guide(으)로 돌아가기