SpringBoot - 无法解析 @RunWith - 找不到符号

a_s*_*ber 3 build.gradle spring-boot

SpringBoot 项目。

在 build.gradle 中:

dependencies {
    implementation 'com.google.code.gson:gson:2.7'
    implementation 'com.h2database:h2'
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    implementation('com.squareup.retrofit2:retrofit:2.4.0')
    implementation('com.squareup.retrofit2:converter-gson:2.4.0')
    implementation group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'

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

test {
    useJUnitPlatform()
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试课:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;

@RunWith(SpringRunner.class)
@DataJpaTest
public class CategoryRepositoryIntegrationTest {
    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    private CategoryRepository productRepository;
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

error: cannot find symbol

@RunWith(SpringRunner.class)
 ^
  symbol: class RunWith
1 error
FAILURE: Build failed with an exception
Run Code Online (Sandbox Code Playgroud)

fla*_*xel 8

您混合了 JUnit 4 和 5。您使用 JUnit 5 中的 Test 注释,而 RunWith 注释来自 JUnit 4。我建议使用 JUnit 5。为此,您只需要用以下行替换 RunWith:

@ExtendWith(SpringExtension.class)
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用 SpringBoot 2.1 或更早版本,您可以删除 RunWith 注释,它也应该可以工作。