How to write the unit test when using GeoCoordinates class with/without initializing the Navigate Engine
Since GeoCoordinates class in the HERE SDK is declared as final, Mockito won't be able to mock it directly because Mockito cannot mock final classes by default. Please follow to workaround this limitation and suggest to our customers:
1. Use Mockito's Inline Mock Maker (Since Mockito 2.1.0)
Mockito introduced an inline mock maker feature that allows mocking of final classes/methods in our case since GeoCoordinates class is final. To enable this feature, we need to add a configuration file to our project:
Create a text file named org.mockito.plugins.MockMaker in your project's src/test/resources/mockito-extensions directory.
Add a single line to this file: mock-maker-inline.
This tells Mockito to use the inline mock maker, which supports mocking of final classes and methods.
2. Create a Wrapper Class
Another approach is to create a non-final wrapper class around GeoCoordinates and then mock that wrapper class.
Here's an example of how to implement and test a wrapper class:
public class GeoCoordinatesWrapper {
private final GeoCoordinates geoCoordinates;
public GeoCoordinatesWrapper(double latitude, double longitude) {
this.geoCoordinates = new GeoCoordinates(latitude, longitude);
}
public double getLatitude() {
return geoCoordinates.getLatitude();
}
public double getLongitude() {
return geoCoordinates.getLongitude();
}
}
// In our test class
import org.mockito.Mockito;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GeoCoordinatesWrapperTest {
@Test
public void testGeoCoordinatesWrapper() {
// Create a mock of GeoCoordinatesWrapper
GeoCoordinatesWrapper mockGeoCoordinatesWrapper = Mockito.mock(GeoCoordinatesWrapper.class);
// Define behavior for the mock to return specific latitude and longitude
Mockito.when(mockGeoCoordinatesWrapper.getLatitude()).thenReturn(52.53086);
Mockito.when(mockGeoCoordinatesWrapper.getLongitude()).thenReturn(13.38469);
// Use the mock in our test
double latitude = mockGeoCoordinatesWrapper.getLatitude();
double longitude = mockGeoCoordinatesWrapper.getLongitude();
// Assert that the returned values are as expected
assertEquals(52.53086, latitude, 0.00001);
assertEquals(13.38469, longitude, 0.00001);
}
}
In this approach, we're testing with a wrapper class that delegates calls to the actual GeoCoordinates object. This allows us to mock the behavior of the wrapper class in our tests.
Customers can integrate the above in this example from GitHub - https://github.com/heremaps/here-sdk-examples/tree/master/examples/latest/navigate/android/Java/UnitTesting