亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有多個參數的 Spring Boot 集成測試模擬 bean 方法返回 null

具有多個參數的 Spring Boot 集成測試模擬 bean 方法返回 null

繁花不似錦 2022-07-20 21:06:28
我有簡單的帶有Controller,和類的 Spring Boot 應用程序Service,所以我試圖模擬bean 中的方法,它接受四個參數但它返回BusinessUtilMockUtilnull模擬主控制器@RestControllerpublic class MockMainController {@Autowiredprivate MockBusiness mockBusiness;@GetMapping("request")public MockOutput mockRequest() {    return mockBusiness.businessLogic(new MockInput());    } }模擬業務@Servicepublic class MockBusiness {@Autowiredprivate MockService mockService;public MockOutput businessLogic(MockInput input) {    return mockService.serviceLogic(input);    } }模擬服務@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();         }     } }下面是我的簡單測試類,當mockUtil.exchange調用任何方法時,我想基于返回對象ParameterizedTypeReference<T>模擬控制器測試@SpringBootTest@ActiveProfiles("test")@Profile("test")@RunWith(SpringRunner.class)public class MockControllerTest {@Autowiredprivate MockMainController mockMainController;@MockBeanprivate MockUtil mockUtil;
查看完整描述

1 回答

?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

看來您匹配的方式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")));

經過幾次測試后,如果您不使用eqMockito 似乎期望傳遞的實例與 inParameterizedTypeReference相同,并且它只是檢查它是否代表相同的泛型類型。given(..)eq


檢查此問題以獲取更多詳細信息。


查看完整回答
反對 回復 2022-07-20
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號