spring-boot - 测试从服务类返回 ResponseEntity 的方法 - Spring boot
问题描述
我有一个返回 ResponseEntity<> 的服务方法,当我测试其余端点时,它总是返回低于错误。错误表示它没有返回预期的 json。
java.lang.AssertionError: No value at JSON path "$.status"
这是我正在使用的方法
@Test
void Should_ReturnOk_When_VerifyOtpIsSuccessful() throws Exception {
ResponseWrapper responseWrapper =
new ResponseWrapper(ResponseStatusType.SUCCESS, "SUCCESSFULLY_VERIFIED", null);
ResponseEntity<ResponseWrapper> responseWrapperResponseEntity =new ResponseEntity<>(responseWrapper,HttpStatus.ACCEPTED);
when(otpService.verifySmsOtp(otpVerifyRequestDto)).thenReturn(responseWrapperResponseEntity);
this.mockMvc.perform(MockMvcRequestBuilders
.post(OTP_VERIFY_URI)
.contentType(MediaType.APPLICATION_JSON)
.header("app-key", "xxxx")
.content(asJsonString(otpVerifyRequestDto)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status", is("S")))
;
}
这里 ResponseWrapper 是一个模型类
@Getter
public class ResponseWrapper {
private ResponseStatusType status;
private String message;
private String data;
public ResponseWrapper(ResponseStatusType statusType, String message, String data) {
this.status = statusType;
this.message = message;
this.data = data;
}
}
你能帮我解决这个问题吗?
编辑:
似乎 ResponseEntity 不返回 JSON 本身,它有其他对象
感谢您对此的意见。
测试类初始化
@AutoConfigureMockMvc
public class OtpControllerTest {
@Mock
private OtpServiceImpl otpService;
private Validator validator = new Validator();
private OtpRequestDto otpRequestDtoEmail = otpRequestDto();
private OtpVerifyRequestDto otpVerifyRequestDto = otpVerifyRequestDto();
@InjectMocks
private OtpController otpController;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
otpController = new OtpController(otpService, validator);
this.mockMvc = MockMvcBuilders.standaloneSetup(otpController).build();
}
// test methods here
//
}
谢谢你。
解决方案
推荐阅读
- python - 将数据框转换为另一个数据框,将复合字符串单元格拆分为单独的行
- node.js - 如何确保在变量赋值之前返回数据(Node.js)
- ssl-certificate - Fetchmail 和服务器证书验证错误:无法获取本地颁发者证书
- entity-framework - 当我使用 Web 部署发布到登台时,为什么我的迁移不会自动执行?
- c# - xaml resourcedictionary 内容设置器前景未正确显示
- python-3.x - 如何在python中使用子进程模块安装程序(.exe)
- android - 原生脚本 | 无法运行 Android 应用:请通过更新 google-services 插件的版本来修复版本冲突
- php - Jquery和Bootstrap 4 dataTable删除第2页上的行不起作用
- python - 演员评论家政策损失为零(没有改善)
- angular - Angular Observables DialogWindow SyncFusion