Springboot Mockito:模拟服务方法返回空体

Springboot Mockito : Mocked service method returning empty body

我有以下球衣控制器。

  @POST
  @ApiOperation(value = "", response = Certification.class)
  public Response addCertification(@Valid CertificationRequest request) {
    return Response.ok(certificationService.addCertification(request)).build();
  }

然后我使用 Mockito 和 SpringRunner 开发了以下测试。

@Test
    public void givenValidToken_whenAddingCertification_thenCorrect() {
        CertificationRequest certificationRequest = new CertificationRequest();
        certificationRequest.setName("name");
        Certification certification = new Certification();
        when(certificationService.addCertification(certificationRequest)).thenReturn(certification);

        given()
                .contentType(ContentType.JSON)
                .body(certificationRequest)
                .when()
                .post("/certifications")
                .then()
                .assertThat()
                .statusCode(200)
                .contentType(ContentType.JSON)
                .log()
                .all();
    }

就这么写的,执行的时候出现如下错误

HTTP/1.1 200 
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 0
Date: Fri, 26 Jun 2020 18:33:35 GMT

java.lang.AssertionError: 1 expectation failed.
Expected content-type "JSON" doesn't match actual content-type "".

另一方面,如果我添加 null 代替 certificationRequest 并在 RestAssured 中发送一个空主体,它工作正常。

为什么它 return 与请求正文一起发送时是空的正文?

您的至少一个问题是:

when(certificationService.addCertification(certificationRequest)).thenReturn(certification);

您需要一个 Matcher 而不是 certificationRequest。如果你想匹配任何请求,你可以使用 ArgumentMatchers.any()。如果你想检查一个特定的请求,你可以使用 ArgumentMatchers.eq(certificationRequest)。请注意 ArgumentMatchers.eq(...) 仅在您提供了有效的 equals 方法(或者如果您传递了完全相同的参数,公平)时才有效。

例如:

when(certificationService.addCertification(ArgumentMatchers.eq(certificationRequest))).thenReturn(certification);

如果这不能解决您的问题,我会尝试打印响应并检查您得到了什么。