Is it possible to test methods of serviceA and tell the test environment to replace all calls from serviceA to serviceB with a mockServiceB?
This is the method I´d like to test (ServiceA.java):
@Inject
ServiceB serviceB;
public boolean tokenExists(ItemModel item) throws Exception {
try {
List<ItemModel > items = serviceB.getItems();
String token = item.getToken();
return items.stream().filter(i -> i.getToken().equals(token)).findFirst().isPresent();
} catch (ApiException e) {
throw new Exception(500, "Data could not be fetched.", e);
}
}
Since serviceB.getItems() will result in a REST-call, I'd like to replace calls to serviceB with a custom mockServiceB where I just load mock data from a json file like this (TestServiceA.java):
@InjectMock
ServiceB serviceB;
@ApplicationScoped
public static class ServiceB {
private ObjectMapper objMapper = new ObjectMapper();;
public List<ItemModel> getItems() throws IOException {
final String itemsAsJson;
try {
itemsAsJson= IOUtils.toString(new FileReader(RESOURCE_PATH + "items.json"));
objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Item> items= objMapper.readValue(itemsAsJson, objMapper.getTypeFactory().constructCollectionType(List.class, ItemModel.class));
return items;
} catch (IOException e) {
throw e;
}
}
}
And then test the tokenExists method like this (TestServiceA.java):
@Test
public void testTokenExists() {
try {
Assertions.assertTrue(this.serviceA.tokenExists(this.getTestItem()));
} catch (Exception e) {
fail("exception");
}
}
However, when I run the test testTokenExists it still calls the original serviceB.getItems(). So my question would be if this is even possible or if I have to take a different approach.