我有簡單的帶有Controller,和類的 Spring Boot 應(yīng)用程序Service,所以我試圖模擬bean 中的方法,它接受四個(gè)參數(shù)但它返回BusinessUtilMockUtilnull模擬主控制器@RestControllerpublic class MockMainController {@Autowiredprivate MockBusiness mockBusiness;@GetMapping("request")public MockOutput mockRequest() { return mockBusiness.businessLogic(new MockInput()); } }模擬業(yè)務(wù)@Servicepublic class MockBusiness {@Autowiredprivate MockService mockService;public MockOutput businessLogic(MockInput input) { return mockService.serviceLogic(input); } }模擬服務(wù)@Servicepublic class MockService {@Autowiredprivate MockUtil mockUtil;public MockOutput serviceLogic(MockInput input) { ResponseEntity<MockOutput> res = mockUtil.exchange(UriComponentsBuilder.fromUriString(" "), HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<MockOutput>() { }); return res.getBody(); } }模擬工具@Componentpublic class MockUtil {@Autowiredprivate RestTemplate restTemplate;public <T> ResponseEntity<T> exchange(UriComponentsBuilder uri, HttpMethod method, HttpEntity<?> entity, ParameterizedTypeReference<T> typeReference) { try { ResponseEntity<T> response = restTemplate.exchange(uri.toUriString(), method, entity, typeReference); return response; } catch (HttpStatusCodeException ex) { System.out.println(ex); return new ResponseEntity<T>(ex.getStatusCode()); } catch (Exception ex) { ex.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }下面是我的簡單測試類,當(dāng)mockUtil.exchange調(diào)用任何方法時(shí),我想基于返回對象ParameterizedTypeReference<T>模擬控制器測試@SpringBootTest@ActiveProfiles("test")@Profile("test")@RunWith(SpringRunner.class)public class MockControllerTest {@Autowiredprivate MockMainController mockMainController;@MockBeanprivate MockUtil mockUtil;
1 回答

一只斗牛犬
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊
看來您匹配的方式ParameterizedTypeReference不起作用。它與您期望的不匹配。
嘗試以下操作:
given(mockUtil
.exchange(
ArgumentMatchers.any(),
ArgumentMatchers.any(),
ArgumentMatchers.any(),
// eq matches to any param of the same generic type
ArgumentMatchers.eq(new ParameterizedTypeReference<MockOutput>(){})))
.willReturn(ResponseEntity.ok().body(new MockOutput("hello", "success")));
經(jīng)過幾次測試后,如果您不使用eqMockito 似乎期望傳遞的實(shí)例與 inParameterizedTypeReference相同,并且它只是檢查它是否代表相同的泛型類型。given(..)eq
檢查此問題以獲取更多詳細(xì)信息。
添加回答
舉報(bào)
0/150
提交
取消