【问题标题】:SpringBoot - Can't resolve @RunWith - cannot find symbolSpringBoot - 无法解析@RunWith - 找不到符号
【发布时间】:2020-09-10 17:34:58
【问题描述】:

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()
}

这是我的测试类:

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;

但我得到错误:

error: cannot find symbol

@RunWith(SpringRunner.class)
 ^
  symbol: class RunWith
1 error
FAILURE: Build failed with an exception

【问题讨论】:

    标签: spring-boot build.gradle


    【解决方案1】:

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

    @ExtendWith(SpringExtension.class)
    

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

    【讨论】:

      【解决方案2】:

      我从 Spring boot doc 中找到了这个,不确定对您的问题有帮助。

      如果您使用的是 JUnit 4,请不要忘记将 @RunWith(SpringRunner.class) 也添加到您的测试中,否则注释将被忽略。如果您使用的是 JUnit 5,则无需将等效的 @ExtendWith(SpringExtension.class) 添加为 @SpringBootTest 并且其他 @…Test 注释已使用它进行注释。

      这里是链接https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/html/boot-features-testing.html 并检查第 46.3 节

      【讨论】:

        【解决方案3】:

        只需添加

        @SpringBootTest
        

        并删除其他注释

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-11
          • 2021-08-26
          相关资源
          最近更新 更多