如何正确地模拟我的RestTemplate单元测试?



我当前使用RestTemplate到达GET端点的单元测试有很多硬编码的值。我想知道是否有更好的方法来嘲笑价值观,以及如何做到这一点。目前看起来是这样的:

@RunWith(MockitoJUnitRunner.class)
public class CarServiceTest {
private final String uri = "https://cars.com/cars";
private final String token = "xxx";
private List<Car> carList;
private Cars testCars;
@Mock
private RestTemplate restTemplate;
@InjectMocks
private CarService carService;
@BeforeAll
void init() {
carList = new ArrayList<>(Arrays.asList(new Car("car1")));
testCars = new Cars(carList);
}
@Test
public void test_getCars() {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
Mockito.when(restTemplate.exchange(
RequestEntity.get(new URI(uri)).headers(headers).build(),
Cars.class))
.thenReturn(new ResponseEntity(testCars, HttpStatus.OK));
Cars returnedCars = carService.getCars();
// assertion
Assert.assertEquals(testCars, returnedCars);
// verify
verify(restTemplate).exchange(RequestEntity
.get(new URI(uri)).headers(headers).build(),
Cars.class);
verifyNoMoreInteractions(restTemplate);
}
}

我正在寻找关于如何改进测试中使用的对象的初始化/模拟的建议。(我目前在测试中使用真实的URL和令牌)

您可以使用MockRestServiceServer

RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build();
server.expect(MockRestRequestMatchers.requestTo(uri))
.andExpect(requestTo(uri))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(new ObjectMapper()
.writeValueAsString(cars), MediaType.APPLICATION_JSON));

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
restTemplate.exchange(RequestEntity.get(new URI(uri)).headers(headers).build(), Cars.class))
server.verify();

你可以设置你需要的存根,也可以验证你所期望的调用实际上发生在几行代码中,并且在IMO中更加清晰。

相关内容

  • 没有找到相关文章

最新更新