|
| 1 | +package com.thealgorithms.geometry; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | + |
| 5 | +import java.util.stream.Stream; |
| 6 | +import org.junit.jupiter.api.DisplayName; |
| 7 | +import org.junit.jupiter.params.ParameterizedTest; |
| 8 | +import org.junit.jupiter.params.provider.Arguments; |
| 9 | +import org.junit.jupiter.params.provider.MethodSource; |
| 10 | + |
| 11 | +/** |
| 12 | + * Unit tests for the Haversine formula implementation. |
| 13 | + * This class uses parameterized tests to verify the distance calculation |
| 14 | + * between various geographical coordinates. |
| 15 | + */ |
| 16 | +final class HaversineTest { |
| 17 | + |
| 18 | + // A small tolerance for comparing double values, since floating-point |
| 19 | + // arithmetic is not always exact. A 1km tolerance is reasonable for these distances. |
| 20 | + private static final double DELTA = 1.0; |
| 21 | + |
| 22 | + /** |
| 23 | + * Provides test cases for the haversine distance calculation. |
| 24 | + * Each argument contains: lat1, lon1, lat2, lon2, and the expected distance in kilometers. |
| 25 | + * |
| 26 | + * @return a stream of arguments for the parameterized test. |
| 27 | + */ |
| 28 | + static Stream<Arguments> haversineTestProvider() { |
| 29 | + return Stream.of( |
| 30 | + // Case 1: Distance between Paris, France and Tokyo, Japan |
| 31 | + Arguments.of(48.8566, 2.3522, 35.6895, 139.6917, 9712.0), |
| 32 | + |
| 33 | + // Case 2: Distance between New York, USA and London, UK |
| 34 | + Arguments.of(40.7128, -74.0060, 51.5074, -0.1278, 5570.0), |
| 35 | + |
| 36 | + // Case 3: Zero distance (same point) |
| 37 | + Arguments.of(52.5200, 13.4050, 52.5200, 13.4050, 0.0), |
| 38 | + |
| 39 | + // Case 4: Antipodal points (opposite sides of the Earth) |
| 40 | + // Should be approximately half the Earth's circumference (PI * radius) |
| 41 | + Arguments.of(0.0, 0.0, 0.0, 180.0, 20015.0)); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Tests the haversine method with various sets of coordinates. |
| 46 | + * |
| 47 | + * @param lat1 Latitude of the first point. |
| 48 | + * @param lon1 Longitude of the first point. |
| 49 | + * @param lat2 Latitude of the second point. |
| 50 | + * @param lon2 Longitude of the second point. |
| 51 | + * @param expectedDistance The expected distance in kilometers. |
| 52 | + */ |
| 53 | + @ParameterizedTest |
| 54 | + @MethodSource("haversineTestProvider") |
| 55 | + @DisplayName("Test Haversine distance calculation for various coordinates") |
| 56 | + void testHaversine(double lat1, double lon1, double lat2, double lon2, double expectedDistance) { |
| 57 | + double actualDistance = Haversine.haversine(lat1, lon1, lat2, lon2); |
| 58 | + assertEquals(expectedDistance, actualDistance, DELTA); |
| 59 | + } |
| 60 | +} |
0 commit comments