← Назад к вопросам

Как исключить зависимость из spring-boot-starter-test

1.3 Junior🔥 141 комментариев
#Другое

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Как исключить зависимость из spring-boot-starter-test

Некоторые зависимости в spring-boot-starter-test могут быть не нужны для вашего проекта или конфликтовать с другими. Maven и Gradle предоставляют несколько способов их исключения.

1. Исключение через Maven (pom.xml)

Используй элемент <exclusion> внутри <dependency>:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2. Исключение через Gradle (build.gradle)

Используй блок exclude в конфигурации зависимости:

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    exclude group: 'org.mockito', module: 'mockito-core'
    exclude group: 'org.hamcrest', module: 'hamcrest'
}

// Или альтернативный синтаксис
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude(group: 'org.junit.vintage', module: 'junit-vintage-engine')
}

3. Практические примеры исключения

<!-- Исключение JUnit Vintage если используешь только JUnit 5 -->
<exclusion>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
</exclusion>

<!-- Исключение Mockito если используешь spy с mock-util -->
<exclusion>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
</exclusion>

<!-- Исключение AssertJ если используешь другую библиотеку утверждений -->
<exclusion>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
</exclusion>

<!-- Исключение JSONPath если не нужна проверка JSON -->
<exclusion>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
</exclusion>

4. Что входит в spring-boot-starter-test

spring-boot-starter-test содержит:

├── JUnit 4 & 5 (junit-vintage-engine + junit-jupiter)
├── Mockito (mockito-core + mockito-junit-jupiter)
├── AssertJ (assertions library)
├── Spring Test & Spring Boot Test
├── JSONPath (json assertions)
├── XMLUnit (xml assertions)
└── Hamcrest (matcher library)

5. Проверка исключенных зависимостей

Проверь, какие зависимости на самом деле подключены:

# Maven
mvn dependency:tree | grep test

# Gradle
./gradlew dependencies --configuration testRuntimeClasspath | grep -A5 spring-boot-starter-test

6. Сценарии исключения

Сценарий 1: Если в проекте уже есть JUnit

<!-- Исключи vendor-specific реализации -->
<exclusion>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
</exclusion>

Сценарий 2: Если используешь TestNG вместо JUnit

<exclusion>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
</exclusion>
<exclusion>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
</exclusion>

Сценарий 3: Если используешь PowerMock вместо Mockito

<exclusion>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
</exclusion>
<exclusion>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
</exclusion>

7. Полный пример project setup

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <!-- Используем TestNG, не JUnit -->
        <exclusion>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
        
        <!-- Используем PowerMock для testing private методов -->
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </exclusion>
        
        <!-- Используем TruthAssert вместо AssertJ -->
        <exclusion>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- Добавляем необходимые нам зависимости -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.8.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-testng</artifactId>
    <version>2.0.9</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.google.truth</groupId>
    <artifactId>truth</artifactId>
    <version>1.1.3</version>
    <scope>test</scope>
</dependency>

8. Gradle полный пример

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.jupiter'
    exclude group: 'org.junit.vintage'
    exclude group: 'org.mockito'
    exclude group: 'org.assertj'
}

// Добавляем свои библиотеки
testImplementation 'org.testng:testng:7.8.0'
testImplementation 'org.powermock:powermock-module-testng:2.0.9'
testImplementation 'com.google.truth:truth:1.1.3'

9. Потенциальные проблемы

// ⚠️ После исключения Mockito могут быть ошибки
@SpringBootTest
public class UserServiceTest {
    
    @MockBean  // ← Требует mockito-junit-jupiter
    private UserRepository userRepository;
    
    // Решение: добавь mockito-junit-jupiter явно
}

10. Best Practices

  1. Исключай минимально — чем меньше исключений, тем проще поддерживать
  2. Задокументируй причины — почему исключены зависимости
  3. Добавляй замены явно — если нужна другая библиотека, добавь её сразу
  4. Проверяй конфликты — убедись, что исключенные зависимости не нужны другим модулям
  5. Версионируй правильно — поддерживай совместимость версий замены
<!-- Хорошо: с комментарием -->
<exclusion>
    <!-- Исключаем Mockito т.к. используем PowerMock который обёрнут вокруг Mockito -->
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
</exclusion>

Исключение зависимостей — это нормальная практика, когда проект имеет особые требования к тестовому фреймворку.

Как исключить зависимость из spring-boot-starter-test | PrepBro