Flush a method with an object parameter using Mockito

In my unit test, I want to scoff at interacting with elasticsearch by doing the following

when(cityDefinitionRepository.findCitiesNearby(geoPoint, SOURCE, 2)).thenReturn(cityDefinitionsArrival); when(cityDefinitionRepository.findCitiesNearby(geoPoint2, SOURCE, 2)).thenReturn(cityDefinitionsDeparture); SearchResult results = benerailService.doSearch(interpretation, 2, false); 

doSearch method contains

 departureCityDefinitions = cityDefinitionRepository.findCitiesNearby(geo, SOURCE, distance); 

When I debug my code, I see that mockito is called in my doSearch method, but it does not return the cityDefinitionsArrival object. This is probably due to the fact that geoPoint and geo are two different objects.

Geo flows and geo objects are geosynthetic elasticsearch objects that contain the same latitude and longitude.

I managed to get this to work by doing

 when(cityDefinitionRepository.findCitiesNearby(any(geoPoint.getClass()), eq(SOURCE), eq(2))).thenReturn(cityDefinitionsArrival); when(cityDefinitionRepository.findCitiesNearby(any(geoPoint2.getClass()), eq(SOURCE), eq(2))).thenReturn(cityDefinitionsDeparture); 

But now it ignores my latitude and longitude values ​​and accepts any object of the GeoPoint class. This is a problem because in my doSearch method I have two options for findCitiesNearby, each with a different latitude and longitude, and I need to simulate them individually.

Is this possible with Mockito?

CityDefinitionsArrival and cityDefinitionsDeparture are both ArrayLists, SOURCE is a string value and the geo and geoPoint object are:

 GeoPoint geoPoint = new GeoPoint(50.850449999999995, 4.34878); GeoPoint geoPoint2 = new GeoPoint(48.861710, 2.348923); double lat = 50.850449999999995; double lon = 4.34878; GeoPoint geo = new GeoPoint(lat, lon); double lat2 = 48.861710; double lon2 = 2.348923; GeoPoint geo2 = new GeoPoint(lat2, lon2); 
+5
source share
1 answer

Use argThat :

 public final class IsSameLatLong extends ArgumentMatcher<GeoPoint> { private final GeoPoint as; public IsSameLatLong(GeoPoint as) { this.as = as; } //some sensible value, like 1000th of a second ie 0Β° 0' 0.001" private final static double EPSILON = 1.0/(60*60*1000); private static boolean closeEnough(double a, double b) { return Math.abs(a - b) < EPSILON; } public boolean matches(Object point) { GeoPoint other = (GeoPoint) point; if (other == null) return false; return closeEnough(other.getLat(), as.getLat()) && closeEnough(other.getLong(), as.getLong()); } } 

Then use like this:

 when(cityDefinitionRepository.findCitiesNearby(argThat(new IsSameLatLong(geoPoint)), eq(SOURCE), eq(2))).thenReturn(cityDefinitionsArrival); when(cityDefinitionRepository.findCitiesNearby(argThat(new IsSameLatLong(geoPoint2)), eq(SOURCE), eq(2))).thenReturn(cityDefinitionsDeparture); 
+4
source

Source: https://habr.com/ru/post/1239768/


All Articles