【问题标题】:Springboot test fails to autowire TestRestTemplate when using junit5使用junit5时Spring Boot测试无法自动装配TestRestTemplate
【发布时间】:2020-06-22 23:37:54
【问题描述】:

我使用的是springboot 2.2.2.RELEASE版本。

我正在尝试使用 junit5 添加测试,这是我在 build.gradle 中的设置方式:

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'junit', module: 'junit'
}
testImplementation "org.junit.jupiter:junit-jupiter-api:5.5.2"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.5.2"

这是我的测试课:

//@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, classes = UserServiceApplication.class)
@ActiveProfiles("it")
public class UserControllerIntegrationTest {
    @Autowired
    private TestRestTemplate testRestTemplate;

}

问题是restRestTemplate 为空。它起作用的唯一方法是当我使用时:

@RunWith(SpringRunner.class)

不过,据我了解,这是为了支持junit4,对吧?

我正在使用未弃用的 TestRestTemplate (org.springframework.boot.test.web.client.TestRestTemplate)。

我也尝试添加以下内容,但也没有用:

@ExtendWith(SpringExtension.class)

我错过了什么?

谢谢。

【问题讨论】:

    标签: spring-boot spring-boot-test


    【解决方案1】:

    确保您的整个测试都使用了与 JUnit 5 相关的注解。也许您的 @Test 注释仍在使用 JUnit 4。

    The following example works for JUnit 5 and Spring Boot:
    
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.test.context.junit.jupiter.SpringExtension;
    
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    @ExtendWith(SpringExtension.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = YourApplication.class)
    public class TestOne {
    
      @Autowired
      private TestRestTemplate testRestTemplate;
    
      @Test
      public void test() {
        assertNotNull(testRestTemplate);
      }
    }
    

    【讨论】:

    • 谢谢。在我念出其他注释之后,我遇到了另一个问题,但我需要添加 build.gradle 以下内容:test { useJUnitPlatform() }。现在的问题是,我有用 spock 编写的单元测试,它们没有运行,我收到一个错误:没有找到给定包含的测试
    • 我找到了这个blog.jdriven.com/2018/10/combining-spock-junit-5-tests 我会尝试看看我是否可以将它们组合在一起,我会在这里更新以供将来参考。
    猜你喜欢
    • 2020-02-09
    • 2017-01-05
    • 2020-03-24
    • 2018-02-09
    • 2014-07-30
    • 1970-01-01
    • 2016-03-29
    • 2019-01-14
    • 2017-11-15
    相关资源
    最近更新 更多