如何在 JUnit 5 中使用 @RestTemplateClient?

     2023-02-27     215

关键词:

【中文标题】如何在 JUnit 5 中使用 @RestTemplateClient?【英文标题】:How to use @RestTemplateClient with JUnit 5? 【发布时间】:2019-12-23 14:51:10 【问题描述】:

我使用 spring boot 2.1.7.RELEASE 和 junit 5。不幸的是,@RestClientTest 有问题,因为我收到 java.lang.IllegalStateException: Unable to use auto-configured MockRestServiceServer since MockServerRestTemplateCustomizer has not be bound to一个休息模板。您对如何正确配置有任何想法吗?

类似的代码在junit 4中完美运行。 源代码基于文档https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html。

源代码:

@RestClientTest(RemoteVehicleDetailsService.class)
public class ExampleRestClientTest 

    @Autowired
    private RemoteVehicleDetailsService service;

    @Autowired
    private MockRestServiceServer server;

    @Test
    public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
            throws Exception 
        this.server.expect(requestTo("/greet/details"))
                .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
        String greeting = this.service.callRestService();
        assertThat(greeting).isEqualTo("hello");
    

例外:

java.lang.IllegalStateException: Unable to use auto-configured MockRestServiceServer since MockServerRestTemplateCustomizer has not been bound to a RestTemplate

    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerAutoConfiguration$DeferredRequestExpectationManager.getDelegate(MockRestServiceServerAutoConfiguration.java:110)
    at org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerAutoConfiguration$DeferredRequestExpectationManager.expectRequest(MockRestServiceServerAutoConfiguration.java:87)
    at org.springframework.test.web.client.MockRestServiceServer.expect(MockRestServiceServer.java:107)
    at org.springframework.test.web.client.MockRestServiceServer.expect(MockRestServiceServer.java:92)
    at ExampleRestClientTest.getVehicleDetailsWhenResultIsSuccessShouldReturnDetails(ExampleRestClientTest.java:27)```

【问题讨论】:

【参考方案1】:

我使用最后一个 spring boot 2.1.7 和 junit 5 测试了您的案例,一切正常。请尝试:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zpavel</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
            <version>1.4.199</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

application.properties(我使用了 h2 内存数据库):

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

FooService.java:

@Service
public class FooService 

    private final RestTemplate restTemplate;

    public FooService(RestTemplateBuilder restTemplateBuilder) 
        this.restTemplate = restTemplateBuilder.build();
    

    public String getIndex() 
        String result = restTemplate.getForObject("http://localhost:8080", String.class);
        System.out.println("index: " + result);
        return result;
    

FooServiceTest.java:

@RestClientTest(FooService.class)
public class FooServiceTest 

    @Autowired
    private FooService service;

    @Autowired
    private MockRestServiceServer server;

    @Test
    public void testIndex() throws Exception 
        this.server.expect(requestTo("http://localhost:8080")).andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
        String greeting = this.service.getIndex();
        assertEquals(greeting, "hello");
    

【讨论】:

请注意导入:import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;导入静态 org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;导入静态 org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;【参考方案2】:

spring MockMvc 对你有用吗?

@Autowired
private MockMvc mockMvc;

public void test() 
    this.mockMvc.perform(get("/form")
            .header(AUTHORIZATION, authHeader))
            .andDo(print())
            .andExpect(status().isOk());

【讨论】:

在 Junit 5 中,如何从扩展中调用测试类方法?

】在Junit5中,如何从扩展中调用测试类方法?【英文标题】:InJunit5howcanIcallatestclassmethodfromanextension?【发布时间】:2021-02-0721:25:15【问题描述】:在Junit5中,我试图让测试类方法从扩展中运行。我正在使用Junit5扩展接口TestWatcher... 查看详情

如何在 JUnit 5 中替换 WireMock @Rule 注释?

】如何在JUnit5中替换WireMock@Rule注释?【英文标题】:HowtoreplaceWireMock@RuleannotationinJUnit5?【发布时间】:2018-12-0308:55:16【问题描述】:我在我的测试中使用了WireMock并且有这样一行代码:@RulepublicWireMockRulewireMockRule=newWireMockRule(8080);... 查看详情

在 JUnit 5 中,如何在所有测试之前运行代码

】在JUnit5中,如何在所有测试之前运行代码【英文标题】:InJUnit5,howtoruncodebeforealltests【发布时间】:2017-09-0302:44:38【问题描述】:@BeforeAll注释标记了一个方法,该方法要在一个类中的所有测试之前运行。http://junit.org/junit5/docs/c... 查看详情

JUnit 5:如何断言抛出异常?

】JUnit5:如何断言抛出异常?【英文标题】:JUnit5:Howtoassertanexceptionisthrown?【发布时间】:2017-03-0904:24:42【问题描述】:在JUnit5中有没有更好的方法来断言方法抛出异常?目前,我必须使用@Rule来验证我的测试是否引发了异常,... 查看详情

如何使用 JUnit 5 在 Kotlin 中创建 TestContainers 基测试类

】如何使用JUnit5在Kotlin中创建TestContainers基测试类【英文标题】:HowtocreateaTestContainersbasetestclassinKotlinwithJUnit5【发布时间】:2019-09-2915:58:30【问题描述】:我正在尝试将Neo4jTestContainers与Kotlin、SpringDataNeo4j、SpringBoot和JUnit5一起使... 查看详情

在 JUnit 5 中使用 @TestContainers 实现 @DataJpaTest

】在JUnit5中使用@TestContainers实现@DataJpaTest【英文标题】:Spring@DataJpaTestwith@TestContainersinJUnit5【发布时间】:2021-03-1500:32:04【问题描述】:这是对Spring@DataJpaTestwithJUnit5的扩展,主要区别在于添加了测试容器。我试图在git-reposample中... 查看详情

如何在 JUnit5 中使用 Mockito

】如何在JUnit5中使用Mockito【英文标题】:HowtouseMockitowithJUnit5【发布时间】:2017-04-1901:36:39【问题描述】:如何在Mockito和JUnit5中使用注入?在JUnit4中,我可以只使用@RunWith(MockitoJUnitRunner.class)注释。在JUnit5中是没有@RunWith注解?【... 查看详情

如何使 Spring 的 @Autowired 在 JUnit 5 扩展中工作? [复制]

】如何使Spring的@Autowired在JUnit5扩展中工作?[复制]【英文标题】:HowtomakeSpring\'s@AutowiredtoworkinJUnit5extensions?[duplicate]【发布时间】:2019-01-1318:54:40【问题描述】:我有一个SpringBoot应用程序,我正在尝试在JUnit5扩展中使用@Autowired。... 查看详情

如何使用 junit 5 为 Eclipse 编写测试套件?

】如何使用junit5为Eclipse编写测试套件?【英文标题】:Howtowriteatestsuitewithjunit5foreclipse?【发布时间】:2021-05-0709:04:10【问题描述】:我正在尝试通过测试套件中的junit5测试运行。但是我得到一个错误importorg.junit.platform.runner.JUnitPl... 查看详情

如何在用 Kotlin 编写的 JUnit 5 测试类中注入 Spring bean?

】如何在用Kotlin编写的JUnit5测试类中注入Springbean?【英文标题】:HowtoinjectaSpringbeaninaJUnit5testclasswritteninKotlin?【发布时间】:2019-06-0412:32:51【问题描述】:我尝试使用JUnit5和SpringBoot在Kotlin项目中测试某些内容,但我无法在我的... 查看详情

如何将 Gradle 中的原生 JUnit 5 支持与 Kotlin DSL 结合使用?

】如何将Gradle中的原生JUnit5支持与KotlinDSL结合使用?【英文标题】:HowdoIusethenativeJUnit5supportinGradlewiththeKotlinDSL?【发布时间】:2018-10-1205:08:41【问题描述】:我想将内置JUnit5与GradleKotlinDSL一起使用,因为在构建过程中我收到以下... 查看详情

如何使用 Gradle 和 JUnit 5 仅运行特定测试?

】如何使用Gradle和JUnit5仅运行特定测试?【英文标题】:HowtorunonlyspecifictestswithGradleandJUnit5?【发布时间】:2018-07-2008:41:15【问题描述】:使用Gradle及其对JUnit4的支持,我可以使用--tests选项选择特定测试,如下所示:$./gradlewtest--t... 查看详情

如何使用 Junit 在 servlet 中测试业务逻辑?

】如何使用Junit在servlet中测试业务逻辑?【英文标题】:HowdoItestbusinesslogicinaservletusingJunit?【发布时间】:2022-01-2110:00:48【问题描述】:我有一个servlet,它在调用DAO方法之前进行一些前置条件检查,如下所示:privatevoidprocessReques... 查看详情

当 JUnit 5 没有 assertThat() 函数时,如何将 Hamcrest 与 JUnit 5 一起使用?

】当JUnit5没有assertThat()函数时,如何将Hamcrest与JUnit5一起使用?【英文标题】:HowdoIuseHamcrestwithJUnit5whenJUnit5doesn\'thaveanassertThat()function?【发布时间】:2017-09-0223:08:03【问题描述】:要将Hamcrest与JUnit4一起使用,我们使用assertThat()... 查看详情

如何在 Junit 中使用 @InjectMocks 和 @Autowired 注释

】如何在Junit中使用@InjectMocks和@Autowired注释【英文标题】:Howtouse@InjectMocksalongwith@AutowiredannotationinJunit【发布时间】:2016-03-0804:23:03【问题描述】:我有一个A类,它使用3个不同的自动装配类publicclassA()@AutowiredprivateBb;@Autowiredprivat... 查看详情

如何在 JUnit 测试中使用 Spring defaultValidator

】如何在JUnit测试中使用SpringdefaultValidator【英文标题】:HowtouseSpringdefaultValidatorinJUnittests【发布时间】:2022-01-1306:08:12【问题描述】:我一直在我的测试类上使用@SpringJunitConfig来减少@SpringBootTest的上下文加载时间。这在我只使用... 查看详情

如何使用eclipse进行junit测试

使用eclipse进行junit测试的方法:1、将JUnit4单元测试包引入这个项目:在该项目上点右键,点“属性”,如图:2、在弹出的属性窗口中,首先在左边选择“JavaBuildPath”,然后到右上选择“Libraries”标签,之后在最右边点击“AddLib... 查看详情

java示例代码_如何在Servlet和JSP中使用JUnit

java示例代码_如何在Servlet和JSP中使用JUnit 查看详情