首页 > 解决方案 > Springboot Mockito:模拟服务方法返回空主体

问题描述

我有以下球衣控制器。

  @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 中发送一个空正文,它工作正常。

为什么与请求正文一起发送时返回一个空正文?

标签: springjunitautomated-testsmockitorest-assured

解决方案


至少您的问题之一如下:

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

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

例如:

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

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


推荐阅读