具有多个参数的 Spring 启动集成测试模拟 Bean 方法返回 null



我有一个简单的弹簧启动应用程序,其中包含ControllerServiceBusinessUtil类,所以我试图在 bean 中模拟该方法MockUtil该方法,该方法需要四个参数,但它返回null

模拟主控制器

@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>返回对象

模拟控制器测试

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

经过几次测试后,似乎如果您不使用eqMockito,则期望传递的ParameterizedTypeReferencegiven(..)中的实例相同,并且使用eq它只会检查它是否表示相同的泛型类型。

有关更多详细信息,请查看此问题。

最新更新