Reputation: 1
I’m working on unit testing a Java method that interacts with external HTTP destinations and performs HTTP requests. I’m having difficulty covering the method with JUnit tests due to its dependencies on external services.
Here is the method I need to test: import static com.sap.cloud.sdk.cloudplatform.connectivity.DestinationAccessor.getDestination;
public String getResponseAsString(String path) {
HttpDestinationProperties httpDestination = getDestination(destinationName()).asHttp();
HttpClient client = getHttpClient(httpDestination);
try {
String requestUrl = httpDestination.getUri() + HttpClientUtils.replaceSpecialSymbolsForIpSystem(path);
log.info("GET response as a string: {} ", requestUrl);
return client.execute(new HttpGet(requestUrl), getResponseHandler());
} catch (IOException e) {
log.error(CONNECTION_ABORTED, e.getMessage());
}
return EMPTY;
}
My challenges:
Mocking getDestination(destinationName()).asHttp(): How can I mock the destination and its properties?
What I’ve tried:
I attempted to use Mockito for mocking, but I'm unsure how to properly mock the getDestination and HttpClient methods.
This junits throws error: Destination Access exception: failed to get destination
junits I tried:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DestinationAccessor.class})
public class HttpDestinationClientTest {
@Mock
private HttpClient httpClient;
@Mock
private HttpDestinationProperties httpDestination;
@Mock
private Destination destination;
@Mock
private DestinationAccessor destinationAccessor;
@InjectMocks
private HttpDestinationClient client = new HttpDestinationClient() {
@Override
protected String destinationName() {
return "mockDestination";
}
};
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(DestinationAccessor.class);
HttpDestination mockHttpDestination = Mockito.mock(HttpDestination.class);
Destination mockDestination = mock(Destination.class);
when(mockDestination.asHttp()).thenReturn(mockHttpDestination);
when(DestinationAccessor.getDestination("mockDestination")).thenReturn((mockDestination));
}
@Test
public void testGetResponseAsString() throws IOException, InterruptedException {
client.getResponseAsString("/path");
}
}
Upvotes: 0
Views: 96
Reputation: 563
You can use the builder API to create a destination with the properties you need for your test case. Not sure what you want to test exactly, but typically that is sufficient.
In case you are trying to mock the static DestinationAccessor.getDestination
method, I'd recommend to instead refactor your code to not rely on mocking this method.
Still, if you feel mocking this method is required, you can use:
var mock = DefaultHttpDestination.builder("foo.com").build();
DestinationLoader loader = (name, opts) -> Try.success(mock);
DestinationAccessor.setLoader(loader);
Upvotes: 0