使用junit5时,Springboot测试无法自动连接TestRestTemplate

用户名

我正在使用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为null。它唯一有效的方法是在使用时:

@RunWith(SpringRunner.class)

但是,以我的理解,这是对junit4的支持,对吗?

我正在使用不推荐使用的TestRestTemplate(org.springframework.boot.test.web.client.TestRestTemplate)。

我还尝试添加以下内容,但也无法正常工作:

@ExtendWith(SpringExtension.class)

我想念什么?

谢谢。

里克皮尔

确保整个测试使用的是与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);
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法使用Maven执行Junit5测试

使用Mockito和jUnit5的SpringBoot Controller测试失败,因为Spring无法创建可加载属性的PropertyService类的bean?

使用Junit5在Spring Boot应用程序中测试服务层时如何避免数据库连接

MapStruct无法通过Spring-boot测试Gradle Junit5自动工作

使用带有 jUnit5 和 SpringBoot 的随机端口进行契约测试

无法使用JUnit5控制台启动器运行测试

无法在Docker容器中使用Bazel运行JUnit5测试

无法使用Spring Boot Gradle插件通过依赖项管理执行junit5测试

使用JUnit5和Spring-boot-starter-parent时不执行任何测试

Maven surefire插件无法检测Junit5测试

测试服务时 JUnit5 SpringBootTest NullPointerException

如何使用SpringBoot2,JUnit5和Kotlin将配置属性注入到单元测试中

尝试使用Maven运行Mockito junit5测试时,java.lang.NoClassDefFoundError:org / junit / platform / commons / PreconditionViolationException

在JUnit5中使用Testcontainers和gradle时,无法解析“ DockerImageName”中的方法“ parse”

使用 JUNIT5 测试用例处理多个异常

使用Junit5进行Gradle多项目集成测试

如何使用 JUnit5 在 OpenEJB 中测试 EJB Bean?

无法运行测试类“未找到测试运行程序‘Junit5’的测试”

正确配置JUNIT5以进行测试

JUnit5:如何重复失败的测试?

Maven不会运行JUnit5测试

测试中的JUnit5断言计数

如何在多模块项目中使用 JUnit5 和 SpringBoot2 通过 gradle 而不是 intelliJ 运行测试

在junit5上使用测试服测试多个类即将挂起

Java异常没有测试中发现匹配时Junit5 ParameterizedTest尝试

为什么Eclipse在应使用JUnit4时尝试使用JUnit5?

JUnit Jupiter(JUnit5)中的参数化测试执行

如何使用JUnit5为Kafka消息使用者测试PACT

在SpringBoot项目上使用DBUNIT运行Junit测试时出错