Issue
I have a Spring application which gets data from an API. We test over Jenkins and the problem is that Jenkins doesn't have access to this API.
So our solution is to embedded some sample files with these API endpoints, to src/test/resources
.
But the code is becoming a mess since I don't know how to differ if it's testing or running.
For example:
private void loadDataFromEndpointOne(boolean isTest) {
List<String> someData = new ArrayList<>();
if (isTest) {
ClassLoader loader = this.getClass().getClassLoader();
String file = loader.getResource("endpointOne.txt");
...
someData = someMethodReadingResourceFile();
}
else {
someData = someMethodReadingFromAPI();
}
}
So, from JUnit @Test
I set isTest
as true and from runtime false.
This does not sound elegant to me.
Is there a clever way?
Solution
If you are writing JUnit test its better to use Mockito or PowerMockito (or any other librbrary for that matter) to mock the API call. Thats the cleaner way of doing JUnit tests. For example if you have :
private void loadDataFromEndpointOne() {
someData = someMethodReadingFromAPI();
}
Mock it like this from your test class :
Mockito.when(mockedClass.loadDataFromEndpointOne()).thenReturn(someDummyDataForTest);
For more info you can refer Mockito's doc.
Answered By - raviiii1