Giriş
3 taraf API'leri test etmek için WireMock kullanmak zorunda değiliz.
1. Test kodunda 3 taraf API'yi taklit eden ama localhost üzerinde çalışan kod yazılır
2. RestTemplate localhost'a yönlendirilir
Elimizde şöyle bir kod olsun
// application.propertiesdownstream.basepath=https://dev.faas.neuw.io/function// SpringBootApplication.java@Beanpublic RestTemplate restTemplate(@Value("${downstream.basepath}") String rootUri) {return new RestTemplateBuilder().rootUri(rootUri).build();}@RestControllerpublic class UpstreamController {private final DownstreamClientService downstreamClientService;@GetMapping("/v1/upstream")public Pong test() {return downstreamClientService.getPong();}}@Servicepublic class DownstreamClientService {private final RestTemplate restTemplate;public Pong getPong() {return restTemplate.getForObject("/ping", Pong.class);}}
test içinde şöyle yaparız.
Test yine UpstreamController nesnesin tetikler.
O da DownstreamClientService nesnesini tetikler.
O da RestTemplate localhost'u işaret ettiği için localhost üzerindeki ping servisini tetikler
// src/test/resources/application.properties
# on this port the unit tests will run
server.port=58080
downstream.basepath=http://localhost:${server.port}
//SpringBootApplicationTests.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class SpringBootApplicationTests {
@Autowired
TestRestTemplate testRestTemplate;
@Test
void testPong() {
Pong res = testRestTemplate.getForObject("/v1/upstream", Pong.class);
assertEquals(true, res.isSuccess());
assertEquals("pong", res.getMessage());
}
}
@RestController
public class DownstreamMockController {
@GetMapping("ping")
public Pong test() {
logger.info("for testing only, downstream hosted from the test package's controller");
return new Pong("pong", true, new Date().getTime(), true);
}
}
Hiç yorum yok:
Yorum Gönder