I've been mainly working on Angular and frontend so far and just got into the world of Java Spring to enhance my backend skills. I need to implement the WebClient to do REST calls and was able to do the implementation but stuck on the test class. This is what I have so far:
...codeset/service/impl/CodesetService.java:
@Component
public class CodesetService {
private final WebClient codesetClient;
@Autowired
public CodesetService (@Qualifier("codesetClient") final WebClient codesetClient, RestConfiguration restConfig) {
this.codesetClient = codesetClient;
}
protected List<CodeAll> getCodeset(String codesetName, TracingInfo tracingInfo) {
return codesetClient
.get()
.uri(builder -> builder.queryParam("codeset", codesetName).build())
.headers(headers -> createHttpHeadersConsumer(tracingInfo))
.retrieve()
.bodyToFlux(CodeAll.class)
.collectList()
.block();
}
}
...codeset/rest/RestConfiguration.java:
@Configuration
public class RestConfiguration {
private final String codesetServiceUrl;
private final String codeAllPath;
public RestConfiguration(
@Value("${codeset-service.url}") String codesetServiceUrl,
@Value("${codeset-service.codeAllPath}") String codeAllPath
) {
this.codesetServiceUrl = codesetServiceUrl;
this.codeAllPath = codeAllPath;
}
@Bean("codesetClient")
public WebClient codesetClient() {
final var builder =
new WebClientBuilder(
codesetServiceUrl + codeAllPath,
null,
null,
null,
null,
Optional.empty(),
Optional.empty());
return builder.build();
}
public String getCodesetServiceUrl() {
return codesetServiceUrl;
}
public String getCodeAllPath() {
return codeAllPath;
}
}
Does this look correct to you so far?
Then, in the test class, how to implement the WebClient mock using Mockito? See the comment in the code block.
...codeset/service/impl/CodesetServiceTest.java:
class CodesetServiceTest {
@Mock
WebClient codesetClient;
private List<CodeAll> createCodeList(String code) {
return Collections.singletonList(
CodeAll.builder().code(code).endDate(LocalDate.now().plusDays(1)).build());
}
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
underTest =
new CodesetService(
codesetClient, restConfig);
when(restConfig.getCodesetServiceUrl()).thenReturn("getCodesetServiceUrl");
when(restConfig.getCodeAllPath()).thenReturn("/getCodeAllPath");
// Here, how to call the "getCodesetServiceUrl/getCodeAllPath?codeset=code-set-name" using Mockito?
// Response type would be <List<CodeAll>> and return: createCodeList("code")
}
}
Any help would be appreciated!