首页 > 解决方案 > 测试从服务类返回 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
//
}

谢谢你。

标签: spring-bootunit-testingmockitomockmvc

解决方案


推荐阅读