spring - 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 中发送一个空正文,它工作正常。
为什么与请求正文一起发送时返回一个空正文?
解决方案
至少您的问题之一如下:
when(certificationService.addCertification(certificationRequest)).thenReturn(certification);
您需要一个 Matcher 而不是 CertificationRequest。如果您想匹配任何请求,您可以使用ArgumentMatchers.any()
. 如果您想检查特定的请求,您可以使用ArgumentMatchers.eq(certificationRequest)
. 请注意, ArgumentMatchers.eq(...) 仅在您提供了有效的 equals 方法时才有效(或者如果您传递完全相同的参数,公平)。
例如:
when(certificationService.addCertification(ArgumentMatchers.eq(certificationRequest))).thenReturn(certification);
如果那不能解决您的问题,我会尝试打印响应并检查您得到的结果。
推荐阅读
- python - 标记熊猫数据框中日期范围内的日期时间列表
- javascript - 为什么我的测验无法在触摸屏上开始?
- android-arrayadapter - 在listview android java中使用毕加索设置imageview
- react-native - 布尔数组作为复选框值?
- php - 在 sql 查询中选择具有多个 OR 的 DISTINCT
- java - 有没有办法在没有 AsyncPlayerChatEvent 的情况下捕捉玩家聊天输入?
- python - 如何确保终止多处理池?
- c# - 在 Asp.NET Web Forms Endpoint 上发送 Ajax 请求时收到错误(内部服务器错误)
- c# - 如何用 oledb 调用 as400 存储过程?
- android - AndroidX Preferences 异常:“您需要在此活动中使用 Theme.AppCompat 主题(或后代)。”