popov . dev

Main

Library

Articles

Базовый Spring b...

Базовый Spring boot тест с использованием Junit 5

Тестирование Java-приложения Spring Boot с использованием JUnit 5 включает в себя настройку тестовых зависимостей, написание тестовых примеров и их запуск. Мы представили пошаговое руководство, которое поможет вам в этом процессе

1. Настройка зависимостей

Во-первых, убедитесь, что ваш pom.xml (для Maven) или build.gradle (для Gradle) включает необходимые зависимости для Spring Boot и JUnit 5.

Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>

Gradle:

dependencies {
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.junit.jupiter:junit-jupiter-api'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

2. Создайте базовое приложение Spring Boot

Создайте простое приложение Spring Boot с базовым сервисом и контроллером для тестирования.

Сервис:

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String greet(String name) {
        return "Привет, " + name;
    }
}

Контроллер:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @Autowired
    private GreetingService greetingService;

    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        return greetingService.greet(name);
    }
}

3. Напишите тест кейсы

Теперь давайте напишем несколько тестовых примеров с использованием JUnit 5.

Тест для сервиса:

package com.example.demo;

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

import org.junit.jupiter.api.Test;

class GreetingServiceTest {

    private final GreetingService greetingService = new GreetingService();

    @Test
    void testGreet() {
        String result = greetingService.greet("Мир");
        assertEquals("Привет, Мир", result);
    }
}

Тест для контроллера:

Для тестирования контроллера нам нужно использовать аннотации @SpringBootTest и @AutoConfigureMockMvc для загрузки контекста и автоматической настройки MockMvc.

package com.example.demo;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
class GreetingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testGreet() throws Exception {
        mockMvc.perform(get("/greet").param("name", "Мир"))
                .andExpect(status().isOk())
                .andExpect(content().string("Привет, Мир"));
    }
}

4. Выполнение тестов

Вы можете запускать свои тесты, используя встроенную поддержку JUnit в вашей IDE или используя команды Maven/Gradle.

Maven:

mvn test

Grandle:

gradle test

Comments

In order to leave your opinion, you need to register on the website