There are a few mistakes here, and this shows that you misunderstand the mockery. Let them analyze them:
At first, I hope this is a mistake with the last error, you do not have @RunWith(PowerMockRunner.class)
, otherwise you will get one more exception.
The second point, this line is commented out correctly when(GeocodingApi.newRequest(geoApiContext)).thenReturn(geocodingApiRequest);
. When the static method is GeocodingApi
, then you want to return geocodingApiRequest
.
Finally, but the most important point, this line is incorrect: when(GeocodingApi.newRequest(geoApiContext).latlng(latLng).await()).thenReturn(geocodingResults);
Only one static call will laugh here: GeocodingApi.newRequest(geoApiContext)
.
And the instance of the actual object will be returned, because you are creating a new instance of GeocodingApiRequest geocodingApiRequest = new GeocodingApiRequest(geoApiContext);
.
The latlng(latLng)
method is called from a valid object. And he really calls, not mocks. But it seems to me that you also want to mock it.
Then let's cast it: GeocodingApiRequest geocodingApiRequest = mock(GeocodingApiRequest.class);
After. make fun of all the challenges you need to mock:
when(geocodingApiRequest.latlng(latLng)).thenReturn(geocodingApiRequest); when(geocodingApiRequest.await()).thenReturn(geocodingResults);
Another error, but as important as the previous and more obvious: the required files are not installed for geocodingResult
.
GeocodingResult geocodingResult = new GeocodingResult(); geocodingResult.types = new AddressType[]{ AddressType.LOCALITY}; geocodingResult.formattedAddress = "Some address";
Full working test:
@RunWith(PowerMockRunner.class) @PrepareForTest({GeocodingApi.class, GeocodingApiRequest.class}) public class GoogleApiServiceUnitTest { private static final Double LATITUDE = -38.010403; private static final Double LONGITUDE = -57.558408; @Mock private GeoApiContext geoApiContext; @InjectMocks private GoogleApiService googleApiService; @Test public void testGetLocalityFromLatLng() throws Exception { LatLng latLng = new LatLng(LATITUDE, LONGITUDE); GeocodingResult geocodingResult = new GeocodingResult(); geocodingResult.types = new AddressType[]{ AddressType.LOCALITY}; geocodingResult.formattedAddress = "Some address"; GeocodingResult[] geocodingResults = new GeocodingResult[] { geocodingResult }; GeocodingApiRequest geocodingApiRequest = mock(GeocodingApiRequest.class); when(geocodingApiRequest.latlng(latLng)).thenReturn(geocodingApiRequest); when(geocodingApiRequest.await()).thenReturn(geocodingResults); mockStatic(GeocodingApi.class); when(GeocodingApi.newRequest(eq(geoApiContext))) .thenReturn(geocodingApiRequest); String locality = googleApiService.getLocalityFromLatLng(latLng); assertThat(locality, is(notNullValue())); verifyStatic(times(1)); GeocodingApi.newRequest(geoApiContext);