我有一个简单的Spring Boot应用程序,其中包含Controller
,Service
,Business
和Util
类,因此我试图在MockUtil
中模拟该方法具有四个参数但返回null
MockMainController
@RestController
public class MockMainController {
@Autowired
private MockBusiness mockBusiness;
@GetMapping("request")
public MockOutput mockRequest() {
return mockBusiness.businessLogic(new MockInput());
}
}
MockBusiness
@Service
public class MockBusiness {
@Autowired
private MockService mockService;
public MockOutput businessLogic(MockInput input) {
return mockService.serviceLogic(input);
}
}
MockService
@Service
public class MockService {
@Autowired
private MockUtil mockUtil;
public MockOutput serviceLogic(MockInput input) {
ResponseEntity<MockOutput> res = mockUtil.exchange(UriComponentsBuilder.fromUriString(" "), HttpMethod.GET,
HttpEntity.EMPTY, new ParameterizedTypeReference<MockOutput>() {
});
return res.getBody();
}
}
MockUtil
@Component
public class MockUtil {
@Autowired
private 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>
的对象
MockControllerTest
@SpringBootTest
@ActiveProfiles("test")
@Profile("test")
@RunWith(SpringRunner.class)
public class MockControllerTest {
@Autowired
private MockMainController mockMainController;
@MockBean
private MockUtil mockUtil;
@Test
public void controllerTest() {
given(this.mockUtil.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.any(new ParameterizedTypeReference<MockOutput>() {
}.getClass()))).willReturn(ResponseEntity.ok().body(new MockOutput("hello", "success")));
MockOutput output = mockMainController.mockRequest();
System.out.println(output);
}
}
通过调试,我可以看到mockUtil.exchange
返回了null
答案 0 :(得分:1)
似乎您匹配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")));
经过几次测试,如果您不使用eq
,则Mockito希望传递的ParameterizedTypeReference
与given(..)
中的{strong> instance 相同,并且与{ {1}}只是检查它是否代表相同的泛型类型。
检查this question了解更多详细信息。