'Unit test java Optional with mockito
I want to test a method which returns an Optional client in it.
I want to test the scenario when client is empty.This is not a working code but overall it looks like this
public Optional<String> doSomething(String place) {
Optional<Client> client = Optional.empty();
try {
client = Optional.ofNullable(clientHelper.get(place));
} catch (Ex ex) {
log.warn("Exception occured:", ex);
}
return client.isPresent() ? Optional.ofNullable(client.get().getPlaceDetails(place)) : Optional.empty();
}
I have a helper class clientHelper which returns a client based on place if exists, if not it throws exception. For test, this is what I came up with
@Test
public void testClientHelper(){
ClientHelper clientHelper = Mockito.mock(ClientHelper.class);
Optional<Client> client = Optional.empty();
Mockito.when(Optional.ofNullable(clientHelper.get("IN"))).thenReturn(client);
assertEquals( doSomething("IN"), Optional.empty())
}
But it returns exception -
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Optional cannot be returned by get()
get() should return Client
I have been following this link Mockito error with method that returns Optional<T>
Solution 1:[1]
your problem here is that you are calling when with something that isn't a mock. You are passing it an Optional.
If I understand what you are trying to do here, the clientHelper is passed to the object with the doSomething method and you want to mock it for testing purposes. If that's the case it'd more typically look like this:
interface ClientHelper {
Client get(String place) throws Ex;
}
class ClassUnderTest {
private final ClientHelper clientHelper;
public ClassUnderTest(ClientHelper helper) {
this.clientHelper = helper;
}
public Optional<String> doSomething(String place) {
try {
return Optional.ofNullable(clientHelper.get(place).getPlaceDetails(place));
} catch (Ex ex) {
log.warn("Exception: " + ex);
return Optional.empty();
}
}
}
@Test
void testFullHelper() {
Client client = mock(Client.class);
when(client.getPlaceDetails("IN")).thenReturn("Details");
ClientHelper helper = mock(ClientHelper.class);
when(helper.get("IN")).thenReturn(client);
ClassUnderTest obj = new ClassUnderTest(helper);
assertEquals("Details", obj.doSomething("IN"));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sprinter |
