我有一个带有ControllerServiceBusinessUtil类的简单的Spring Boot应用程序,所以我试图在MockUtil bean中模拟该方法,该方法带有四个参数,但返回null

MockMainController

@RestController
public class MockMainController {

@Autowired
private MockBusiness mockBusiness;

@GetMapping("request")
public MockOutput mockRequest() {
    return mockBusiness.businessLogic(new MockInput());

    }

 }


模拟业务

@Service
public class MockBusiness {

@Autowired
private MockService mockService;

public MockOutput businessLogic(MockInput input) {
    return mockService.serviceLogic(input);
    }

 }


模拟服务

@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();

    }

 }


模拟工具

@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

最佳答案

您匹配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希望传递的ParameterizedTypeReferencegiven(..)是相同的实例,并且对于eq,它只是检查它是否代表相同的泛型类型。

检查this question了解更多详细信息。

10-07 19:01
查看更多