首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用wiremock、放心、Junit5为spring引导rest编写集成测试

如何使用wiremock、放心、Junit5为spring引导rest编写集成测试
EN

Stack Overflow用户
提问于 2022-05-06 11:34:39
回答 1查看 860关注 0票数 0

我有一个基本的spring引导项目rest,我想为rest编写集成测试。技术栈: wiremock,restassured,Junit5。如何继续前进。

EN

回答 1

Stack Overflow用户

发布于 2022-05-06 11:34:39

  1. 首先在pom文件

中添加相关依赖项

  1. 创建基本集成测试类

代码语言:javascript
复制
import io.restassured.RestAssured;
import io.restassured.config.JsonConfig;
import io.restassured.config.LogConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.path.json.config.JsonPathConfig;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.TestPropertySource;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//To start the stub server on random port, use a value of 0
@AutoConfigureWireMock(port = 0, stubs ="classpath:/stubs")
@TestPropertySource(properties = {
        "external-service.host=http://localhost:${wiremock.server.port}"
})
@Import(BaseIntegrationTestClass.TestConfig.class)
public class BaseIntegrationTestClass {

    @LocalServerPort
    int serverPort = 0;

    @BeforeEach
    void setUpRestAssured() {
        RestAssured.port = serverPort;
        RestAssured.config = RestAssuredConfig.newConfig()
                .jsonConfig(JsonConfig.jsonConfig().numberReturnType(JsonPathConfig.NumberReturnType.DOUBLE))
                .logConfig(LogConfig.logConfig().enableLoggingOfRequestAndResponseIfValidationFails());
    }
//override beans of your choice
   @TestConfiguration
    public static class TestConfig {

        @Bean
        @Primary
        public WebServiceTemplate mockWebServiceTemplate() {
            WebServiceTemplate template = mock(WebServiceTemplate.class);
            when(template.getDefaultUri()).thenReturn("/hello");
            return template;
        }

    }
}

  1. 编写测试类

代码语言:javascript
复制
    import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class RestControllerIT extends BaseIntegrationTestClass{

    @Test
    public void testStatusCodePositive() {
        Response response =  RestAssured.given().
                when().
                get("/");
        assertThat(response.statusCode(), equalTo(HttpStatus.OK.value()));
        assertThat(response.body().asString(), equalTo("Hello World"));
    }
}

  1. 您的控制器

代码语言:javascript
复制
import service.ExternalApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourController {

    @Autowired
    private ExternalApiService externalApiService;

    @GetMapping("/")
    public String checkEligibility() {
       return this.ExternalApiService.go();
    }

}

  1. your service

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ExternalApiService {

    private final RestTemplate restTemplate;

    @Value("${external-service.host}")
    private String base;

    ExternalApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String go() {
        return this.restTemplate.getForEntity(this.base + "/activities", String.class)
                .getBody();
    }
}

  1. 在src/main/ -> application.properties文件中有

代码语言:javascript
复制
external-service.host="https://example.org"

在src/test/

  • /stubs文件夹中,您可以对url进行json映射,与rest模板url相同。somename.json

代码语言:javascript
复制
    {
  "request": {
    "urlPathPattern": "/activities",
    "method": "GET"
  },
  "response": {
    "status": 200,
    "body": "Hello World"
  }
}
代码语言:javascript
复制
// for urls with path params /car/garage/{garageNum}/location/{locationNum}
{
  "request": {
    "urlPathPattern": "/car/garage.*/location.*",
    "method": "GET"
  },
  "response": {
    "status": 200,
     "headers": {
      "Content-Type": "application/json"
    },
       "jsonBody": 
     {
     "msg": "hello world",
     }
  }
}

  1. 右键单击It测试文件并运行
  2. Add plugin in build部分以生成报表

代码语言:javascript
复制
       <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.7</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <propertyName>failsafeArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/site/jacoco-it</outputDirectory>
                        </configuration>
                    </execution>
                    <execution>
                        <id>merge-unit-and-integration</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>merge</goal>
                        </goals>
                        <configuration>
                            <fileSets>
                                <fileSet>
                                    <directory>${project.build.directory}</directory>
                                    <includes>
                                        <include>*.exec</include>
                                    </includes>
                                </fileSet>
                            </fileSets>
                            <destFile>${project.build.directory}/jacoco-merged.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>create-merged-report</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.build.directory}/jacoco-merged.exec</dataFile>
                            <outputDirectory>${project.reporting.outputDirectory}/jacoco-merged</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72140829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档