我正在尝试为具有静态方法调用的控制器编写测试类。 我已经使用骆驼生产者模板来获取结果。
我曾尝试过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;
}
如何使用静态方法为此控制器创建单元测试用例?
答案 0 :(得分: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)
最重要的是,静态方法非常简单,因此不需要对其进行模拟。