【问题标题】:Spring Cloud Contract can not produce json in producer sideSpring Cloud Contract 无法在生产者端生成 json
【发布时间】:2020-07-19 11:53:06
【问题描述】:

我想在生产者 API 中使用 Spring Cloud 合约编写合约。

我的控制器看起来像:

@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);
    }

}

请求类:

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

响应(员工)类:

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

public Integer id;

public String fname;

public String lname;

public Double salary;

public String gender;

 }

用 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"
}
  """)

  }
}

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>

和 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);

}

}

生成的测试类:

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");
}

}

现在,当我构建项目时,出现此错误:

[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.

当我使用 Junit4 构建项目时,一切正常,但在使用 Junit5 时我遇到了这个问题。 我该如何解决这个问题?

【问题讨论】:

  • 你能把你的基类和生成的测试和所有的导入一起粘贴吗?
  • 我编辑问题。@MarcinGrzejszczak
  • 你能打印整个堆栈跟踪吗?
  • [错误] 测试运行:1,失败:1,错误:0,跳过:0,经过时间:2.139 秒 to be equal to: 但不是。在 isc.co.ir.contractproducer.ContractVerifierTest.validate_shouldReturnEmployee(ContractVerifierTest.java:31) @MarcinGrzejszczak 我可以通过电子邮件向您发送整个项目
  • 不,谢谢。我看到你得到 500,但不知道为什么。您可以更新问题以获取所有信息吗?

标签: java spring-boot spring-cloud-contract


【解决方案1】:

请删除@SpringBootTest并使用RestAssuredMockMvc.standaloneSetup或离开@SpringBootTest,注入WebApplicationContext并使用RestAssuredMockMvc.webAppContextSetup(context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多