简体   繁体   English

Spring 云合约无法在生产者端生成 json

[英]Spring Cloud Contract can not produce json in producer side

I want to write a contract using spring cloud contract in producer API.我想在生产者 API 中使用 spring 云合同编写合同。

My controller looks like:我的 controller 看起来像:

@PostMapping(value = "/employee")
public ResponseEntity<Employee> getEmployee(@RequestBody Request employeeRequest) {
    Optional<Employee> employee = employeeService.getEmployee(employeeRequest);
    if(employee.isPresent()){
        return ResponseEntity.status(HttpStatus.OK).
                contentType(MediaType.APPLICATION_JSON).body(employee.get());
    }else{
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

Request class:请求 class:

@Setter
@Getter
public class Request {
private Integer id;
 }

Response (Employee) class:响应(员工)class:

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
 public class Employee {

public Integer id;

public String fname;

public String lname;

public Double salary;

public String gender;

 }

Dsl written in groovy:用 groovy 编写的 Dsl:

import org.springframework.cloud.contract.spec.Contract

 Contract.make {
request {
    method 'POST'
    url '/employee'
    headers {
        contentType(applicationJson())
    }
    body(
            id : 25
    )

}
response {
    status 200
    headers {
        contentType(applicationJson())
    }
    body("""
{
    "id":25,
    "fname":"sara",
    "lname":"ahmadi",
    "salary":"25000.00",
    "gender":"F"
}
  """)

  }
}

Plugin in pom.xml: pom.xml 中的插件:

<plugin>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-maven-plugin</artifactId>
            <version>2.2.3.RELEASE</version>
            <extensions>true</extensions>
            <configuration>
                <baseClassForTests>example.co.ir.contractproducer.BaseTestClass</baseClassForTests>
                <testFramework>JUNIT5</testFramework>
            </configuration>
        </plugin>

And BaseTestClass:和 BaseTestClass:

import io.restassured.config.EncoderConfig;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import isc.co.ir.contractproducer.controller.EmployeeController;
import isc.co.ir.contractproducer.model.Employee;
import isc.co.ir.contractproducer.model.Request;
import isc.co.ir.contractproducer.service.EmployeeService;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder;

import java.util.Optional;

@SpringBootTest
public class BaseTestClass {

@Autowired
private EmployeeController employeeController;

@MockBean
private EmployeeService employeeService;

@BeforeEach
public void setup(){

    Employee employee2=new Employee(25,"Adam","Brown",25000.0,"F");
    Request  request = new Request();
    request.setId(25);
    Mockito.when(employeeService.getEmployee(request)).thenReturn(Optional.of(employee2));

    EncoderConfig encoderConfig = new EncoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false);
    RestAssuredMockMvc.config = new RestAssuredMockMvcConfig().encoderConfig(encoderConfig);

    StandaloneMockMvcBuilder standaloneMockMvcBuilder
            = MockMvcBuilders.standaloneSetup(employeeController);
    RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);

}

} }

Generated test class:生成的测试 class:

import isc.co.ir.contractproducer.BaseTestClass;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import      io.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import io.restassured.response.ResponseOptions;

import static    org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;

 @SuppressWarnings("rawtypes")
 public class ContractVerifierTest extends BaseTestClass {

@Test
public void validate_shouldReturnEmployee() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/json")
                .body("{\"id\":25}");

    // when:
        ResponseOptions response = given().spec(request)
                .post("/employee");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/json.*");

    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['id']").isEqualTo(25);
        assertThatJson(parsedJson).field("['fname']").isEqualTo("sara");
        assertThatJson(parsedJson).field("['lname']").isEqualTo("ahmadi");
        assertThatJson(parsedJson).field("['salary']").isEqualTo("25000.00");
        assertThatJson(parsedJson).field("['gender']").isEqualTo("F");
}

} }

Now when I build the project I get this error:现在,当我构建项目时,出现此错误:

[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.469      s <<< FAILURE! - in example.co.ir.contractproducer.ContractVerifierTest
[ERROR] validate_shouldReturnEmployee  Time elapsed: 0.607 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: 

Expecting:
<500>
to be equal to:
<200>
but was not.

When I build project using Junit4 everything is work fine but while using Junit5 I had this problem.当我使用 Junit4 构建项目时,一切正常,但是在使用 Junit5 时我遇到了这个问题。 How can I fix this problem?我该如何解决这个问题?

Please remove @SpringBootTest and use RestAssuredMockMvc.standaloneSetup or leave @SpringBootTest , inject WebApplicationContext and use RestAssuredMockMvc.webAppContextSetup(context)请删除@SpringBootTest并使用RestAssuredMockMvc.standaloneSetup或离开@SpringBootTest ,注入WebApplicationContext并使用RestAssuredMockMvc.webAppContextSetup(context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 云合约:基于合约的测试根本不会在生产者端生成 - Spring cloud contract: tests based on contracts are not generated on producer side at all 如何在 Spring Cloud 合同的生产者上模拟控制器中的服务 - how to mock the service in controller on producer for spring cloud contract Spring Cloud Contract:如何防止Producer破坏消费者? - Spring Cloud Contract: how to prevent Producer to break consumers? 使用 Spring 云合约为云合约端点编写生产者测试 - Writing producer test for cloud contract end point using Spring clound contract 如何使用 Spring Cloud Kafka Stream 3.1 创建生产者 - How can create a producer using Spring Cloud Kafka Stream 3.1 spring 云合同可以处理具有不同响应的重复请求吗? - can spring cloud contract handle repeated request with different response? 我们可以将spring cloud contract请求/响应属性设为可选吗? - can we make spring cloud contract request/response attribute optional? 无法使用 Spring 云合约 Wiremock,无法加载 ApplicationContext - Can not use Spring Cloud Contract Wiremock, Failed to load ApplicationContext Spring 云 stream 功能性生产者/消费者 bean 在 @SpringBootApplication 之外声明时不起作用 - Spring cloud stream functional producer/consumer bean is not working when declared out side of @SpringBootApplication Spring Cloud Contract和Webflux路由 - Spring cloud contract and webflux routing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM