【问题标题】:How to write junit test for a rest controller having static method call如何为具有静态方法调用的休息控制器编写junit测试
【发布时间】:2019-10-25 11:19:44
【问题描述】:

我正在尝试为具有静态方法调用的控制器编写测试类。 我已经使用骆驼生产者模板来获得结果。

我尝试过使用 Mockito,但没有一个对我有用:

@RestController
@Api(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class TestController{

    @Autowired
    ProducerTemplate producerTemplate;
    @ApiOperation(value = "getdata", notes = "", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/getData" )
    public ApiResponse<Data> getData(@RequestBody DataRequest request, @RequestHeader HttpHeaders headers, HttpServletResponse response) {
        return ApiUtil.makeCall(producerTemplate, "direct:getdata", request,
                headers, response);
    }
}


public static ApiResponse makeCall(ProducerTemplate producerTemplate, String routerName, Object request,
                                            HttpHeaders headers, HttpServletResponse response) {
    HashMap<String, Object> headersMap = null;

    ApiResponse apiResponse = producerTemplate.requestBodyAndHeaders(routerName, request, headersMap, ApiResponse.class);

    response.setStatus(apiResponse.getHttpCode());

    return apiResponse;
}

如何使用静态方法为此控制器创建单元测试用例?

【问题讨论】:

    标签: unit-testing spring-boot junit mockito static-classes


    【解决方案1】:

    Mockito 在这里应该没问题(除非 ProducerTemplate 是最终课程):

    @Mock 
    private ProducerTemplate producerTemplateStub;
    
    @InjectMocks
    private TestController testConstrollerSUT;
    
    @Test
    public void test() throws Exception(){
    
        // Arrange
        when(producerTempalteStub.requestBodyAndHeaders(
               eq(routerName), eq(request), any(Map.class), eq(ApiResponse.class)))
        .thenReturn(myResponse)
    

    最重要的是静态方法很简单,不需要自己模拟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多