diff --git a/build.gradle b/build.gradle index b35b9f557..5f85d9e32 100644 --- a/build.gradle +++ b/build.gradle @@ -72,16 +72,23 @@ android { } applicationVariants.all { variant -> - variant.resValue "string", "applicationId", variant.applicationId + variant.resValue "string", "applicationId", variant.applicationId } } dependencies { implementation 'androidx.appcompat:appcompat:1.0.2' - androidTestImplementation 'androidx.test:runner:1.2.0' - androidTestImplementation 'androidx.test:rules:1.2.0' + androidTestImplementation 'androidx.test:core:1.2.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' + androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0' androidTestImplementation 'androidx.test.ext:junit:1.1.1' - testImplementation 'androidx.test:core:1.2.0' -} + androidTestImplementation 'androidx.test:rules:1.2.0' + androidTestImplementation 'androidx.test:runner:1.2.0' + androidTestImplementation 'org.mockito:mockito-android:3.0.0' + testImplementation 'androidx.test:core:1.2.0' + testImplementation 'org.mockito:mockito-core:3.0.0' + + +} diff --git a/src/androidTest/java/de/dennisguse/opentracks/ChartValueSeriesTest.java b/src/androidTest/java/de/dennisguse/opentracks/ChartValueSeriesTest.java index b1b9d4180..36f39507b 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/ChartValueSeriesTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/ChartValueSeriesTest.java @@ -18,10 +18,9 @@ package de.dennisguse.opentracks; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; -import de.dennisguse.opentracks.R; - import org.junit.Assert; import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; /** @@ -34,7 +33,7 @@ public class ChartValueSeriesTest { private ChartValueSeries series; @Before - protected void setUp() { + public void setUp() { series = new ChartValueSeries( InstrumentationRegistry.getInstrumentation().getContext(), Integer.MIN_VALUE, @@ -46,6 +45,7 @@ public class ChartValueSeriesTest { R.color.chart_elevation_border); } + @Test public void testInitialConditions() { Assert.assertEquals(1, series.getInterval()); Assert.assertEquals(0, series.getMinMarkerValue()); @@ -53,11 +53,13 @@ public class ChartValueSeriesTest { Assert.assertTrue(series.isEnabled()); } + @Test public void testEnabled() { series.setEnabled(false); Assert.assertFalse(series.isEnabled()); } + @Test public void testSmallUpdates() { series.update(0); series.update(10); @@ -67,6 +69,7 @@ public class ChartValueSeriesTest { Assert.assertEquals(500, series.getMaxMarkerValue()); } + @Test public void testBigUpdates() { series.update(0); series.update(901); @@ -76,6 +79,7 @@ public class ChartValueSeriesTest { Assert.assertEquals(5000, series.getMaxMarkerValue()); } + @Test public void testNotZeroBasedUpdates() { series.update(220); series.update(250); diff --git a/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderTest.java b/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderTest.java index 5e440ca49..6a05e9ba6 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderTest.java @@ -19,21 +19,19 @@ package de.dennisguse.opentracks.content; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; -import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; -import de.dennisguse.opentracks.content.CustomContentProvider.DatabaseHelper; - import org.junit.Assert; import org.junit.Before; -import org.junit.runner.RunWith; +import org.junit.Test; + +import de.dennisguse.opentracks.content.CustomContentProvider.DatabaseHelper; /** * Tests {@link CustomContentProvider}. * * @author Youtao Liu */ -@RunWith(AndroidJUnit4.class) public class CustomContentProviderTest { private static final String DATABASE_NAME = "test.db"; @@ -42,7 +40,7 @@ public class CustomContentProviderTest { private CustomContentProvider customContentProvider; @Before - protected void setUp() { + public void setUp() { InstrumentationRegistry.getInstrumentation().getContext().deleteDatabase(DATABASE_NAME); db = (new DatabaseHelper(InstrumentationRegistry.getInstrumentation().getContext(), DATABASE_NAME)).getWritableDatabase(); customContentProvider = new CustomContentProvider(); @@ -51,6 +49,7 @@ public class CustomContentProviderTest { /** * Tests {@link CustomContentProvider.DatabaseHelper#onCreate(SQLiteDatabase)}. */ + @Test public void testDatabaseHelper_OnCreate() { Assert.assertTrue(hasTable(TracksColumns.TABLE_NAME)); Assert.assertTrue(hasTable(TrackPointsColumns.TABLE_NAME)); @@ -60,6 +59,7 @@ public class CustomContentProviderTest { /** * Tests {@link CustomContentProvider#onCreate(android.content.Context)}. */ + @Test public void testOnCreate() { Assert.assertTrue(customContentProvider.onCreate(InstrumentationRegistry.getInstrumentation().getContext())); } @@ -67,12 +67,11 @@ public class CustomContentProviderTest { /** * Tests {@link CustomContentProvider#getType(Uri)}. */ + @Test public void testGetType() { Assert.assertEquals(TracksColumns.CONTENT_TYPE, customContentProvider.getType(TracksColumns.CONTENT_URI)); - Assert.assertEquals( - TrackPointsColumns.CONTENT_TYPE, customContentProvider.getType(TrackPointsColumns.CONTENT_URI)); - Assert.assertEquals( - WaypointsColumns.CONTENT_TYPE, customContentProvider.getType(WaypointsColumns.CONTENT_URI)); + Assert.assertEquals(TrackPointsColumns.CONTENT_TYPE, customContentProvider.getType(TrackPointsColumns.CONTENT_URI)); + Assert.assertEquals(WaypointsColumns.CONTENT_TYPE, customContentProvider.getType(WaypointsColumns.CONTENT_URI)); } /** diff --git a/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderUtilsImplTest.java b/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderUtilsImplTest.java index 663ed450b..4d2539866 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderUtilsImplTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/content/CustomContentProviderUtilsImplTest.java @@ -20,65 +20,65 @@ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; -import android.test.RenamingDelegatingContext; -import android.test.mock.MockContentResolver; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import de.dennisguse.opentracks.content.ContentProviderUtils.LocationFactory; -import de.dennisguse.opentracks.content.ContentProviderUtils.LocationIterator; -import de.dennisguse.opentracks.content.Waypoint.WaypointType; -import de.dennisguse.opentracks.services.TrackRecordingServiceTest.MockContext; -import de.dennisguse.opentracks.stats.TripStatistics; -import com.google.android.testing.mocking.AndroidMock; -import com.google.android.testing.mocking.UsesMocks; +import androidx.test.core.app.ApplicationProvider; import org.junit.Assert; import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.atomic.AtomicInteger; +import de.dennisguse.opentracks.content.ContentProviderUtils.LocationFactory; +import de.dennisguse.opentracks.content.ContentProviderUtils.LocationIterator; +import de.dennisguse.opentracks.content.Waypoint.WaypointType; +import de.dennisguse.opentracks.stats.TripStatistics; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * A unit test for {@link ContentProviderUtilsImpl}. * * @author Bartlomiej Niechwiej * @author Youtao Liu */ -@RunWith(AndroidJUnit4.class) +@RunWith(MockitoJUnitRunner.class) public class CustomContentProviderUtilsImplTest { private static final String NAME_PREFIX = "test name"; private static final String MOCK_DESC = "Mock Next Waypoint Desc!"; private static final String TEST_DESC = "Test Desc!"; private static final String TEST_DESC_NEW = "Test Desc new!"; - private Context context; + private Context context = ApplicationProvider.getApplicationContext(); private ContentProviderUtils providerUtils; private double INITIAL_LATITUDE = 37.0; private double INITIAL_LONGITUDE = -57.0; private double ALTITUDE_INTERVAL = 2.5; - @Before - protected void setUp() { - MockContentResolver mockContentResolver = new MockContentResolver(); - RenamingDelegatingContext targetContext = new RenamingDelegatingContext( - getContext(), getContext(), "test."); - context = new MockContext(mockContentResolver, targetContext); - CustomContentProvider provider = new CustomContentProvider(); - provider.attachInfo(context, null); - mockContentResolver.addProvider(ContentProviderUtils.AUTHORITY, provider); - setContext(context); + @Mock + private Cursor cursorMock; + @Mock + private ContentResolver contentResolverMock; + + @Before + public void setUp() { providerUtils = ContentProviderUtils.Factory.get(context); providerUtils.deleteAllTracks(context); } + @Test public void testLocationIterator_noPoints() { testIterator(1, 0, 1, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } + @Test public void testLocationIterator_customFactory() { final Location location = new Location("test_location"); final AtomicInteger counter = new AtomicInteger(); @@ -93,46 +93,50 @@ public class CustomContentProviderUtilsImplTest { Assert.assertEquals(15, counter.get()); } + @Test public void testLocationIterator_nullFactory() { try { testIterator(1, 15, 4, false, null); - fail("Expecting IllegalArgumentException"); + Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } + @Test public void testLocationIterator_noBatchAscending() { testIterator(1, 50, 100, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } + @Test public void testLocationIterator_noBatchDescending() { testIterator(1, 50, 100, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } + @Test public void testLocationIterator_batchAscending() { testIterator(1, 50, 11, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } + @Test public void testLocationIterator_batchDescending() { testIterator(1, 50, 11, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } + @Test public void testLocationIterator_largeTrack() { testIterator(1, 20000, 2000, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); } - private List testIterator(long trackId, int numPoints, int batchSize, - boolean descending, LocationFactory locationFactory) { + private List testIterator(long trackId, int numPoints, int batchSize, boolean descending, LocationFactory locationFactory) { long lastPointId = initializeTrack(trackId, numPoints); ((ContentProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize); List locations = new ArrayList(numPoints); - LocationIterator it = providerUtils.getTrackPointLocationIterator( - trackId, -1L, descending, locationFactory); + LocationIterator it = providerUtils.getTrackPointLocationIterator(trackId, -1L, descending, locationFactory); try { while (it.hasNext()) { Location loc = it.next(); @@ -172,8 +176,7 @@ public class CustomContentProviderUtilsImplTest { // Load all inserted locations. long lastPointId = -1; int counter = 0; - LocationIterator it = providerUtils.getTrackPointLocationIterator(id, -1L, false, - ContentProviderUtils.DEFAULT_LOCATION_FACTORY); + LocationIterator it = providerUtils.getTrackPointLocationIterator(id, -1L, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); try { while (it.hasNext()) { it.next(); @@ -194,37 +197,35 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#createTrack(Cursor)}. */ - @UsesMocks(Cursor.class) + @Test public void testCreateTrack() { - Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); int startColumnIndex = 1; int columnIndex = startColumnIndex; - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns._ID)) - .andReturn(columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).andReturn( - columnIndex++); + when(cursorMock.getColumnIndexOrThrow(TracksColumns._ID)).thenReturn(columnIndex++); + when(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).thenReturn(columnIndex++); columnIndex = startColumnIndex; // Id - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + when(cursorMock.isNull(columnIndex++)).thenReturn(false); // Name - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + when(cursorMock.isNull(columnIndex++)).thenReturn(false); long trackId = System.currentTimeMillis(); columnIndex = startColumnIndex; // Id - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); + when(cursorMock.getLong(columnIndex++)).thenReturn(trackId); // Name String name = NAME_PREFIX + trackId; - AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); - AndroidMock.replay(cursorMock); + when(cursorMock.getString(columnIndex++)).thenReturn(name); + Track track = providerUtils.createTrack(cursorMock); Assert.assertEquals(trackId, track.getId()); Assert.assertEquals(name, track.getName()); - AndroidMock.verify(cursorMock); + verify(cursorMock); } /** * Tests the method {@link ContentProviderUtilsImpl#deleteAllTracks(Context)} */ + @Test public void testDeleteAllTracks() { // Insert track, points and waypoint at first. long trackId = System.currentTimeMillis(); @@ -233,32 +234,27 @@ public class CustomContentProviderUtilsImplTest { Waypoint waypoint = new Waypoint(); providerUtils.insertWaypoint(waypoint); ContentResolver contentResolver = context.getContentResolver(); - Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, - TracksColumns._ID); + Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); Assert.assertEquals(1, tracksCursor.getCount()); - Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null, - null, TrackPointsColumns._ID); + Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null, null, TrackPointsColumns._ID); Assert.assertEquals(10, tracksPointsCursor.getCount()); - Cursor waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null, - null, WaypointsColumns._ID); + Cursor waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null, null, WaypointsColumns._ID); Assert.assertEquals(1, waypointCursor.getCount()); // Delete all. providerUtils.deleteAllTracks(context); // Check whether all have been deleted. - tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, - TracksColumns._ID); + tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); Assert.assertEquals(0, tracksCursor.getCount()); - tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null, - null, TrackPointsColumns._ID); + tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null, null, TrackPointsColumns._ID); Assert.assertEquals(0, tracksPointsCursor.getCount()); - waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null, - null, WaypointsColumns._ID); + waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null, null, WaypointsColumns._ID); Assert.assertEquals(0, waypointCursor.getCount()); } /** * Tests the method {@link ContentProviderUtilsImpl#deleteTrack(Context, long)}. */ + @Test public void testDeleteTrack() { // Insert three tracks, points of two tracks and way point of one track. long trackId = System.currentTimeMillis(); @@ -299,6 +295,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getAllTracks()} */ + @Test public void testGetAllTracks() { int initialTrackNumber = providerUtils.getAllTracks().size(); long trackId = System.currentTimeMillis(); @@ -311,6 +308,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getLastTrack()} */ + @Test public void testGetLastTrack() { long trackId = System.currentTimeMillis(); providerUtils.insertTrack(getTrack(trackId, 0)); @@ -320,6 +318,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getTrack(long)} */ + @Test public void testGetTrack() { long trackId = System.currentTimeMillis(); providerUtils.insertTrack(getTrack(trackId, 0)); @@ -329,6 +328,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#updateTrack(Track)} */ + @Test public void testUpdateTrack() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 0); @@ -345,6 +345,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#createContentValues(Waypoint)}. */ + @Test public void testCreateContentValues_waypoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -380,8 +381,7 @@ public class CustomContentProviderUtilsImplTest { waypoint.setLocation(loc); providerUtils.insertWaypoint(waypoint); - ContentProviderUtilsImpl contentProviderUtils = new ContentProviderUtilsImpl( - new MockContentResolver()); + ContentProviderUtilsImpl contentProviderUtils = new ContentProviderUtilsImpl(contentResolverMock); long waypointId = System.currentTimeMillis(); waypoint.setId(waypointId); @@ -396,40 +396,36 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#createWaypoint(Cursor)}. */ - @UsesMocks(Cursor.class) + @Test public void testCreateWaypoint() { - Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); int startColumnIndex = 1; int columnIndex = startColumnIndex; - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns._ID)) - .andReturn(columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.NAME)).andReturn( - columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.TRACKID)).andReturn( - columnIndex++); + when(cursorMock.getColumnIndexOrThrow(WaypointsColumns._ID)).thenReturn(columnIndex++); + when(cursorMock.getColumnIndexOrThrow(WaypointsColumns.NAME)).thenReturn(columnIndex++); + when(cursorMock.getColumnIndexOrThrow(WaypointsColumns.TRACKID)).thenReturn(columnIndex++); columnIndex = startColumnIndex; // Id - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + when(cursorMock.isNull(columnIndex++)).thenReturn(false); // Name - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + when(cursorMock.isNull(columnIndex++)).thenReturn(false); // trackIdIndex - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + when(cursorMock.isNull(columnIndex++)).thenReturn(false); long id = System.currentTimeMillis(); columnIndex = startColumnIndex; // Id - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(id); + when(cursorMock.getLong(columnIndex++)).thenReturn(id); // Name String name = NAME_PREFIX + id; - AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); + when(cursorMock.getString(columnIndex++)).thenReturn(name); // trackIdIndex long trackId = 11L; - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); - AndroidMock.replay(cursorMock); + when(cursorMock.getLong(columnIndex++)).thenReturn(trackId); + Waypoint waypoint = providerUtils.createWaypoint(cursorMock); Assert.assertEquals(id, waypoint.getId()); Assert.assertEquals(name, waypoint.getName()); Assert.assertEquals(trackId, waypoint.getTrackId()); - AndroidMock.verify(cursorMock); + verify(cursorMock); } /** @@ -437,6 +433,7 @@ public class CustomContentProviderUtilsImplTest { * {@link ContentProviderUtilsImpl#deleteWaypoint(Context, long, DescriptionGenerator)} * when there is only one waypoint in the track. */ + @Test public void testDeleteWaypoint_onlyOneWayPoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -473,6 +470,7 @@ public class CustomContentProviderUtilsImplTest { * {@link ContentProviderUtilsImpl#deleteWaypoint(Context, long, DescriptionGenerator)} * when there is more than one waypoint in the track. */ + @Test public void testDeleteWaypoint_hasNextWayPoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -528,6 +526,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getFirstWaypointId(long)}. */ + @Test public void testGetFirstWaypointId() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -547,6 +546,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getNextWaypointNumber(long, WaypointType)}. */ + @Test public void testGetNextWaypointNumber() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -577,6 +577,7 @@ public class CustomContentProviderUtilsImplTest { * Tests the method * {@link ContentProviderUtils#getLastWaypoint(long, WaypointType)}. */ + @Test public void testGetLastStatisticsWaypoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -605,6 +606,7 @@ public class CustomContentProviderUtilsImplTest { * Tests the method {@link ContentProviderUtilsImpl#insertWaypoint(Waypoint)} and * {@link ContentProviderUtilsImpl#getWaypoint(long)}. */ + @Test public void testInsertAndGetWaypoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -621,6 +623,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#updateWaypoint(Waypoint)}. */ + @Test public void testUpdateWaypoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); @@ -639,9 +642,9 @@ public class CustomContentProviderUtilsImplTest { } /** - * Tests the method {@link ContentProviderUtilsImpl#bulkInsertTrackPoint(Location[], - * int, long)}. + * Tests the method {@link ContentProviderUtilsImpl#bulkInsertTrackPoint(Location[], int, long)}. */ + @Test public void testBulkInsertTrackPoint() { // Insert track, point at first. long trackId = System.currentTimeMillis(); @@ -657,74 +660,68 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#createTrackPoint(Cursor)}. */ - @UsesMocks(Cursor.class) + @Test public void testCreateTrackPoint() { - Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); - // Set index. int index = 1; // Id - AndroidMock.expect(cursorMock.getColumnIndex(TrackPointsColumns._ID)).andReturn(index++); + when(cursorMock.getColumnIndex(TrackPointsColumns._ID)).thenReturn(index++); // Longitude - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE)).andReturn( - index++); + when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE)).thenReturn(index++); // Latitude - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE)).andReturn( - index++); + when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE)).thenReturn(index++); // Time - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.TIME)) - .andReturn(index++); + when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.TIME)) + .thenReturn(index++); // Speed - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SPEED)).andReturn( - index++); + when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SPEED)).thenReturn(index++); // Sensor - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_HEARTRATE)).andReturn( - index++); + when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_HEARTRATE)).thenReturn(index++); // Set return value of isNull(). index = 2; // Longitude - AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); + when(cursorMock.isNull(index++)).thenReturn(false); // Latitude - AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); + when(cursorMock.isNull(index++)).thenReturn(false); // Time - AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); + when(cursorMock.isNull(index++)).thenReturn(false); // Speed - AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); + when(cursorMock.isNull(index++)).thenReturn(false); // Sensor - AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); + when(cursorMock.isNull(index++)).thenReturn(false); // Set return value of isNull(). index = 2; // Longitude int longitude = 11; - AndroidMock.expect(cursorMock.getInt(index++)).andReturn(longitude * 1000000); + when(cursorMock.getInt(index++)).thenReturn(longitude * 1000000); // Latitude. int latitude = 22; - AndroidMock.expect(cursorMock.getInt(index++)).andReturn(latitude * 1000000); + when(cursorMock.getInt(index++)).thenReturn(latitude * 1000000); // Time long time = System.currentTimeMillis(); - AndroidMock.expect(cursorMock.getLong(index++)).andReturn(time); + when(cursorMock.getLong(index++)).thenReturn(time); // Speed float speed = 2.2f; - AndroidMock.expect(cursorMock.getFloat(index++)).andReturn(speed); + when(cursorMock.getFloat(index++)).thenReturn(speed); // Sensor byte[] sensor = "Sensor state".getBytes(); - AndroidMock.expect(cursorMock.getBlob(index++)).andReturn(sensor); + when(cursorMock.getBlob(index++)).thenReturn(sensor); - AndroidMock.replay(cursorMock); Location location = providerUtils.createTrackPoint(cursorMock); - Assert.assertEquals((double) longitude, location.getLongitude()); - Assert.assertEquals((double) latitude, location.getLatitude()); - Assert.assertEquals(time, location.getTime()); - Assert.assertEquals(speed, location.getSpeed()); - AndroidMock.verify(cursorMock); + Assert.assertEquals((double) longitude, location.getLongitude(), 0.01); + Assert.assertEquals((double) latitude, location.getLatitude(), 0.01); + Assert.assertEquals(time, location.getTime(), 0.01); + Assert.assertEquals(speed, location.getSpeed(), 0.01); + verify(cursorMock); } /** * Tests the method * {@link ContentProviderUtilsImpl#insertTrackPoint(Location, long)}. */ + @Test public void testInsertTrackPoint() { // Insert track, point at first. long trackId = System.currentTimeMillis(); @@ -738,6 +735,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getFirstTrackPointId(long)}. */ + @Test public void testGetFirstTrackPointId() { // Insert track, point at first. long trackId = System.currentTimeMillis(); @@ -750,6 +748,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getLastTrackPointId(long)}. */ + @Test public void testGetLastTrackPointId() { // Insert track, point at first. long trackId = System.currentTimeMillis(); @@ -762,6 +761,7 @@ public class CustomContentProviderUtilsImplTest { /** * Tests the method {@link ContentProviderUtilsImpl#getLastValidTrackPoint(long)}. */ + @Test public void testGetLastValidTrackPoint() { // Insert track, points at first. long trackId = System.currentTimeMillis(); @@ -777,6 +777,7 @@ public class CustomContentProviderUtilsImplTest { * {@link ContentProviderUtilsImpl#getTrackPointCursor(long, long, int, boolean)} * in descending. */ + @Test public void testGetTrackPointCursor_desc() { // Insert track, points at first. long trackId = System.currentTimeMillis(); @@ -792,6 +793,7 @@ public class CustomContentProviderUtilsImplTest { * {@link ContentProviderUtilsImpl#getTrackPointCursor(long, long, int, boolean)} * in ascending. */ + @Test public void testGetTrackPointCursor_asc() { // Insert track, points at first. long trackId = System.currentTimeMillis(); @@ -803,10 +805,9 @@ public class CustomContentProviderUtilsImplTest { } /** - * Tests the method - * {@link ContentProviderUtilsImpl#getTrackPointLocationIterator(long, long, boolean, LocationFactory)} - * in descending. + * Tests the method {@link ContentProviderUtilsImpl#getTrackPointLocationIterator(long, long, boolean, LocationFactory)} in descending. */ + @Test public void testGetTrackPointLocationIterator_desc() { // Insert track, points at first. long trackId = System.currentTimeMillis(); @@ -815,8 +816,7 @@ public class CustomContentProviderUtilsImplTest { long startTrackPointId = 2L; - LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, - startTrackPointId, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); + LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, startTrackPointId, true, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); for (int i = 1; i >= 0; i--) { Assert.assertTrue(locationIterator.hasNext()); Location location = locationIterator.next(); @@ -831,6 +831,7 @@ public class CustomContentProviderUtilsImplTest { * {@link ContentProviderUtilsImpl#getTrackPointLocationIterator(long, long, boolean, LocationFactory)} * in ascending. */ + @Test public void testGetTrackPointLocationIterator_asc() { // Insert track, point at first. long trackId = System.currentTimeMillis(); @@ -839,8 +840,7 @@ public class CustomContentProviderUtilsImplTest { long startTrackPointId = 2L; - LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, - startTrackPointId, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); + LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, startTrackPointId, false, ContentProviderUtils.DEFAULT_LOCATION_FACTORY); for (int i = 1; i < 10; i++) { Assert.assertTrue(locationIterator.hasNext()); @@ -876,7 +876,6 @@ public class CustomContentProviderUtilsImplTest { * @return created location */ private Location createLocation(int i) { - Location loc = new Location("test"); loc.setLatitude(INITIAL_LATITUDE + (double) i / 10000.0); loc.setLongitude(INITIAL_LONGITUDE - (double) i / 10000.0); @@ -893,10 +892,10 @@ public class CustomContentProviderUtilsImplTest { * @param location the location to be checked */ private void checkLocation(int i, Location location) { - Assert.assertEquals(INITIAL_LATITUDE + (double) i / 10000.0, location.getLatitude()); - Assert.assertEquals(INITIAL_LONGITUDE - (double) i / 10000.0, location.getLongitude()); - Assert.assertEquals((float) i / 100.0f, location.getAccuracy()); - Assert.assertEquals(i * ALTITUDE_INTERVAL, location.getAltitude()); + Assert.assertEquals(INITIAL_LATITUDE + (double) i / 10000.0, location.getLatitude(), 0.01); + Assert.assertEquals(INITIAL_LONGITUDE - (double) i / 10000.0, location.getLongitude(), 0.01); + Assert.assertEquals((float) i / 100.0f, location.getAccuracy(), 0.01); + Assert.assertEquals(i * ALTITUDE_INTERVAL, location.getAltitude(), 0.01); } /** @@ -906,7 +905,6 @@ public class CustomContentProviderUtilsImplTest { */ private void insertTrackWithLocations(Track track) { providerUtils.insertTrack(track); - providerUtils.bulkInsertTrackPoint(track.getLocations().toArray(new Location[0]), track - .getLocations().size(), track.getId()); + providerUtils.bulkInsertTrackPoint(track.getLocations().toArray(new Location[0]), track.getLocations().size(), track.getId()); } } diff --git a/src/androidTest/java/de/dennisguse/opentracks/content/DescriptionGeneratorImplTest.java b/src/androidTest/java/de/dennisguse/opentracks/content/DescriptionGeneratorImplTest.java index 5bb8aa07d..cd498d082 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/content/DescriptionGeneratorImplTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/content/DescriptionGeneratorImplTest.java @@ -19,14 +19,15 @@ package de.dennisguse.opentracks.content; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; -import de.dennisguse.opentracks.stats.TripStatistics; -import de.dennisguse.opentracks.util.StringUtils; -import de.dennisguse.opentracks.R; - import org.junit.Assert; import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; +import de.dennisguse.opentracks.R; +import de.dennisguse.opentracks.stats.TripStatistics; +import de.dennisguse.opentracks.util.StringUtils; + /** * Tests for {@link DescriptionGeneratorImpl}. * @@ -39,14 +40,14 @@ public class DescriptionGeneratorImplTest { private DescriptionGeneratorImpl descriptionGenerator; @Before - protected void setUp() throws Exception { + public void setUp() throws Exception { descriptionGenerator = new DescriptionGeneratorImpl(InstrumentationRegistry.getInstrumentation().getContext()); } /** - * Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track, - * java.util.Vector, java.util.Vector, boolean)}. + * Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track, java.util.Vector, java.util.Vector, boolean)}. */ + @Test public void testGenerateTrackDescription() { Track track = new Track(); TripStatistics stats = new TripStatistics(); @@ -88,6 +89,7 @@ public class DescriptionGeneratorImplTest { /** * Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(TripStatistics)}. */ + @Test public void testGenerateWaypointDescription() { Waypoint waypoint = new Waypoint(); TripStatistics stats = new TripStatistics(); @@ -117,14 +119,14 @@ public class DescriptionGeneratorImplTest { + "Max grade: 42 %\n" + "Min grade: 11 %\n" + "Recorded: " + StringUtils.formatDateTime(InstrumentationRegistry.getInstrumentation().getContext(), START_TIME) + "\n"; - Assert.assertEquals( - expected, descriptionGenerator.generateWaypointDescription(waypoint.getTripStatistics())); + Assert.assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint.getTripStatistics())); } /** * Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder, * int, String)}. */ + @Test public void testWriteDistance() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "
"); @@ -135,6 +137,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int, * String)}. */ + @Test public void testWriteTime() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "
"); @@ -145,6 +148,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder, * int, String)}. */ + @Test public void testWriteSpeed() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeSpeed(1.1, builder, R.string.description_average_speed, "\n"); @@ -155,6 +159,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder, * int, String)}. */ + @Test public void testWriteElevation() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "
"); @@ -165,6 +170,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writePace(double, StringBuilder, int, * String)}. */ + @Test public void testWritePace() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writePace(1.1, builder, R.string.description_average_pace_in_minute, "\n"); @@ -175,6 +181,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)}. */ + @Test public void testWriteGrade() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "
"); @@ -185,6 +192,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)} with a NaN. */ + @Test public void testWriteGrade_nan() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "
"); @@ -195,6 +203,7 @@ public class DescriptionGeneratorImplTest { * Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder, * int, String)} with an infinite number. */ + @Test public void testWriteGrade_infinite() { StringBuilder builder = new StringBuilder(); descriptionGenerator.writeGrade( diff --git a/src/androidTest/java/de/dennisguse/opentracks/content/SearchEngineTest.java b/src/androidTest/java/de/dennisguse/opentracks/content/SearchEngineTest.java index 298af9c07..5d2e99cb2 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/content/SearchEngineTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/content/SearchEngineTest.java @@ -17,26 +17,27 @@ package de.dennisguse.opentracks.content; import android.content.ContentUris; +import android.content.Context; import android.location.Location; import android.net.Uri; -import android.test.RenamingDelegatingContext; -import android.test.mock.MockContentResolver; +import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; -import de.dennisguse.opentracks.content.SearchEngine.ScoredResult; -import de.dennisguse.opentracks.content.SearchEngine.SearchQuery; -import de.dennisguse.opentracks.services.TrackRecordingServiceTest.MockContext; -import de.dennisguse.opentracks.stats.TripStatistics; - import org.junit.After; +import org.junit.Assert; import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import de.dennisguse.opentracks.content.SearchEngine.ScoredResult; +import de.dennisguse.opentracks.content.SearchEngine.SearchQuery; +import de.dennisguse.opentracks.stats.TripStatistics; + /** * Tests for {@link SearchEngine}. * These are not meant to be quality tests, but instead feature-by-feature tests @@ -53,24 +54,18 @@ public class SearchEngineTest { private ContentProviderUtils providerUtils; private SearchEngine engine; - @Before - protected void setUp() { - MockContentResolver mockContentResolver = new MockContentResolver(); - RenamingDelegatingContext targetContext = new RenamingDelegatingContext( - getContext(), getContext(), "test."); - MockContext context = new MockContext(mockContentResolver, targetContext); - CustomContentProvider provider = new CustomContentProvider(); - provider.attachInfo(context, null); - mockContentResolver.addProvider(ContentProviderUtils.AUTHORITY, provider); - setContext(context); + private Context context = ApplicationProvider.getApplicationContext(); + + @Before + public void setUp() { providerUtils = ContentProviderUtils.Factory.get(context); engine = new SearchEngine(providerUtils); } @After - protected void tearDown() throws Exception { - providerUtils.deleteAllTracks(getContext()); + public void tearDown() throws Exception { + providerUtils.deleteAllTracks(context); } private long insertTrack(String title, String description, String category, double distance, long hoursAgo) { @@ -141,6 +136,7 @@ public class SearchEngineTest { return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId); } + @Test public void testSearchText() { // Insert 7 tracks (purposefully out of result order): // - one which won't match @@ -162,11 +158,10 @@ public class SearchEngineTest { ArrayList results = new ArrayList(engine.search(query)); // Title > Description > Category. - assertTrackResults(results, - allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, - categoryMatchId); + assertTrackResults(results, allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, categoryMatchId); } + @Test public void testSearchWaypointText() { // Insert 7 waypoints (purposefully out of result order): // - one which won't match @@ -188,11 +183,10 @@ public class SearchEngineTest { ArrayList results = new ArrayList(engine.search(query)); // Title > Description > Category. - assertWaypointResults(results, - allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, - categoryMatchId); + assertWaypointResults(results, allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId, categoryMatchId); } + @Test public void testSearchMixedText() { // Insert 5 entries (purposefully out of result order): // - one waypoint which will match by description @@ -210,12 +204,13 @@ public class SearchEngineTest { ArrayList results = new ArrayList(engine.search(query)); // Title > Description > Category. - assertEquals(results.toString(), 3, results.size()); + Assert.assertEquals(results.toString(), 3, results.size()); assertTrackResult(trackId, results.get(0)); assertWaypointResult(titleWaypointId, results.get(1)); assertWaypointResult(descriptionWaypointId, results.get(2)); } + @Test public void testSearchTrackDistance() { // All results match text, but they're at difference distances from the user. long farFarAwayId = insertTrack("aa", 0.3); @@ -229,6 +224,7 @@ public class SearchEngineTest { assertTrackResults(results, nearId, farId, farFarAwayId); } + @Test public void testSearchWaypointDistance() { // All results match text, but they're at difference distances from the user. long farFarAwayId = insertWaypoint("aa", 0.3); @@ -255,6 +251,7 @@ public class SearchEngineTest { assertTrackResults(results, recentId, oldId, oldestId); } + @Test public void testSearchWaypointRecent() { // All results match text, but they're were recorded at different times. long oldestId = insertWaypoint("aa", 2); @@ -268,6 +265,7 @@ public class SearchEngineTest { assertWaypointResults(results, recentId, oldId, oldestId); } + @Test public void testSearchCurrentTrack() { // All results match text, but one of them is the current track. long currentId = insertTrack("ab", 1); @@ -280,6 +278,7 @@ public class SearchEngineTest { assertTrackResults(results, otherId, currentId); } + @Test public void testSearchCurrentTrackWaypoint() { // All results match text, but one of them is in the current track. long otherId = insertWaypoint("aa", 1, 456); @@ -293,36 +292,36 @@ public class SearchEngineTest { } private void assertTrackResult(long trackId, ScoredResult result) { - assertNotNull("Not a track", result.track); - assertNull("Ambiguous result", result.waypoint); - assertEquals(trackId, result.track.getId()); + Assert.assertNotNull("Not a track", result.track); + Assert.assertNull("Ambiguous result", result.waypoint); + Assert.assertEquals(trackId, result.track.getId()); } private void assertTrackResults(List results, long... trackIds) { String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results; - assertEquals(results.size(), trackIds.length); + Assert.assertEquals(results.size(), trackIds.length); for (int i = 0; i < results.size(); i++) { ScoredResult result = results.get(i); - assertNotNull(errMsg, result.track); - assertNull(errMsg, result.waypoint); - assertEquals(errMsg, trackIds[i], result.track.getId()); + Assert.assertNotNull(errMsg, result.track); + Assert.assertNull(errMsg, result.waypoint); + Assert.assertEquals(errMsg, trackIds[i], result.track.getId()); } } private void assertWaypointResult(long waypointId, ScoredResult result) { - assertNotNull("Not a waypoint", result.waypoint); - assertNull("Ambiguous result", result.track); - assertEquals(waypointId, result.waypoint.getId()); + Assert.assertNotNull("Not a waypoint", result.waypoint); + Assert.assertNull("Ambiguous result", result.track); + Assert.assertEquals(waypointId, result.waypoint.getId()); } private void assertWaypointResults(List results, long... waypointIds) { String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results; - assertEquals(results.size(), waypointIds.length); + Assert.assertEquals(results.size(), waypointIds.length); for (int i = 0; i < results.size(); i++) { ScoredResult result = results.get(i); - assertNotNull(errMsg, result.waypoint); - assertNull(errMsg, result.track); - assertEquals(errMsg, waypointIds[i], result.waypoint.getId()); + Assert.assertNotNull(errMsg, result.waypoint); + Assert.assertNull(errMsg, result.track); + Assert.assertEquals(errMsg, waypointIds[i], result.waypoint.getId()); } } } diff --git a/src/androidTest/java/de/dennisguse/opentracks/content/WaypointCreationRequestTest.java b/src/androidTest/java/de/dennisguse/opentracks/content/WaypointCreationRequestTest.java index 7ce02fd5e..1aa920645 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/content/WaypointCreationRequestTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/content/WaypointCreationRequestTest.java @@ -19,11 +19,12 @@ import android.os.Parcel; import androidx.test.ext.junit.runners.AndroidJUnit4; -import de.dennisguse.opentracks.content.Waypoint.WaypointType; - import org.junit.Assert; +import org.junit.Test; import org.junit.runner.RunWith; +import de.dennisguse.opentracks.content.Waypoint.WaypointType; + /** * Tests for the WaypointCreationRequest class. * {@link WaypointCreationRequest} @@ -33,6 +34,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class WaypointCreationRequestTest { + @Test public void testTypeParceling() { WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_WAYPOINT; Parcel p = Parcel.obtain(); @@ -46,9 +48,9 @@ public class WaypointCreationRequestTest { Assert.assertNull(copy.getIconUrl()); } + @Test public void testAllAttributesParceling() { - WaypointCreationRequest original = new WaypointCreationRequest( - WaypointType.WAYPOINT, false, "name", "category", "description", "img.png", null); + WaypointCreationRequest original = new WaypointCreationRequest(WaypointType.WAYPOINT, false, "name", "category", "description", "img.png", null); Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); diff --git a/src/androidTest/java/de/dennisguse/opentracks/fragments/ChartFragmentTest.java b/src/androidTest/java/de/dennisguse/opentracks/fragments/ChartFragmentTest.java index e01481858..03614f864 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/fragments/ChartFragmentTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/fragments/ChartFragmentTest.java @@ -21,17 +21,17 @@ import android.location.Location; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import de.dennisguse.opentracks.ChartView; import de.dennisguse.opentracks.TrackStubUtils; import de.dennisguse.opentracks.content.SensorDataSetLocation; -import de.dennisguse.opentracks.content.sensor.Sensor; -import de.dennisguse.opentracks.content.sensor.Sensor.SensorDataSet; +import de.dennisguse.opentracks.content.sensor.SensorDataSet; import de.dennisguse.opentracks.util.UnitConversions; -import org.junit.Assert; -import org.junit.Before; -import org.junit.runner.RunWith; - /** * Tests {@link ChartFragment}. * @@ -45,82 +45,64 @@ public class ChartFragmentTest { private ChartFragment chartFragment; @Before - protected void setUp() { + public void setUp() { chartFragment = new ChartFragment(); chartFragment.setChartView(new ChartView(InstrumentationRegistry.getInstrumentation().getContext())); chartFragment.setTripStatisticsUpdater(TrackStubUtils.INITIAL_TIME); } /** - * Tests the logic to get the incorrect values of sensor in {@link ChartFragment#fillDataPoint(Location, - * double[])} + * Tests the logic to get the incorrect values of sensor in {@link ChartFragment#fillDataPoint(Location, double[])} */ + @Test public void testFillDataPoint_sensorIncorrect() { SensorDataSetLocation sensorDataSetLocation = TrackStubUtils.createSensorDataSetLocation(); // No input. double[] point = fillDataPointTestHelper(sensorDataSetLocation); - Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1]); + Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1], 0.01); // Input incorrect state. // Creates SensorData. - Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder() - .setValue(100).setState(Sensor.SensorState.NONE); - Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder() - .setValue(101).setState(Sensor.SensorState.NONE); - Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder() - .setValue(102).setState(Sensor.SensorState.NONE); - - // Creates SensorDataSet. - SensorDataSet sensorDataSet = sensorDataSetLocation.getSensorDataSet(); - sensorDataSet = sensorDataSet.toBuilder() - .setHeartRate(heartRateData).setCadence(cadenceData).setPower(powerData).build(); + SensorDataSet sensorDataSet = new SensorDataSet(SensorDataSet.DATA_UNAVAILABLE, SensorDataSet.DATA_UNAVAILABLE); sensorDataSetLocation.setSensorDataSet(sensorDataSet); // Test. point = fillDataPointTestHelper(sensorDataSetLocation); - Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1]); + Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1], 0.01); } /** - * Tests the logic to get the correct values of sensor in {@link ChartFragment#fillDataPoint(Location, - * double[])}. + * Tests the logic to get the correct values of sensor in {@link ChartFragment#fillDataPoint(Location, double[])}. */ + @Test public void testFillDataPoint_sensorCorrect() { SensorDataSetLocation sensorDataSetLocation = TrackStubUtils.createSensorDataSetLocation(); // No input. double[] point = fillDataPointTestHelper(sensorDataSetLocation); - Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1]); - Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1]); + Assert.assertEquals(Double.NaN, point[ChartView.HEART_RATE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.CADENCE_SERIES + 1], 0.01); + Assert.assertEquals(Double.NaN, point[ChartView.POWER_SERIES + 1], 0.01); // Creates SensorData. - Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder() - .setValue(100).setState(Sensor.SensorState.SENDING); - Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder() - .setValue(101).setState(Sensor.SensorState.SENDING); - Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder() - .setValue(102).setState(Sensor.SensorState.SENDING); + SensorDataSet sensorDataSet = new SensorDataSet(100, 101, 102); // Creates SensorDataSet. - SensorDataSet sensorDataSet = sensorDataSetLocation.getSensorDataSet(); - sensorDataSet = sensorDataSet.toBuilder() - .setHeartRate(heartRateData).setCadence(cadenceData).setPower(powerData).build(); sensorDataSetLocation.setSensorDataSet(sensorDataSet); // Test. point = fillDataPointTestHelper(sensorDataSetLocation); - Assert.assertEquals(100.0, point[ChartView.HEART_RATE_SERIES + 1]); - Assert.assertEquals(101.0, point[ChartView.CADENCE_SERIES + 1]); - Assert.assertEquals(102.0, point[ChartView.POWER_SERIES + 1]); + Assert.assertEquals(100.0, point[ChartView.HEART_RATE_SERIES + 1], 0.01); + Assert.assertEquals(101.0, point[ChartView.CADENCE_SERIES + 1], 0.01); + Assert.assertEquals(102.0, point[ChartView.POWER_SERIES + 1], 0.01); } /** - * Tests the logic to get the value of metric Distance in {@link ChartFragment#fillDataPoint(Location, - * double[])}. + * Tests the logic to get the value of metric Distance in {@link ChartFragment#fillDataPoint(Location, double[])}. */ + @Test public void testFillDataPoint_distanceMetric() { // By distance. chartFragment.setChartByDistance(true); @@ -159,9 +141,9 @@ public class ChartFragmentTest { } /** - * Tests the logic to get the value of imperial Distance in {@link ChartFragment#fillDataPoint(Location, - * double[])}. + * Tests the logic to get the value of imperial Distance in {@link ChartFragment#fillDataPoint(Location, double[])}. */ + @Test public void testFillDataPoint_distanceImperial() { // By distance. chartFragment.setChartByDistance(true); @@ -186,7 +168,7 @@ public class ChartFragmentTest { Location.distanceBetween(sensorDataSetLocation1.getLatitude(), sensorDataSetLocation1.getLongitude(), sensorDataSetLocation2.getLatitude(), sensorDataSetLocation2.getLongitude(), results); double distance1 = results[0] * UnitConversions.M_TO_KM * UnitConversions.KM_TO_MI; - Assert.assertEquals(distance1, point[0]); + Assert.assertEquals(distance1, point[0], 0.01); // The third location is a new location, and use imperial. SensorDataSetLocation sensorDataSetLocation3 = TrackStubUtils.createSensorDataSetLocation(); @@ -200,30 +182,30 @@ public class ChartFragmentTest { Location.distanceBetween(sensorDataSetLocation2.getLatitude(), sensorDataSetLocation2.getLongitude(), sensorDataSetLocation3.getLatitude(), sensorDataSetLocation3.getLongitude(), results); double distance2 = results[0] * UnitConversions.M_TO_KM * UnitConversions.KM_TO_MI; - Assert.assertEquals(distance1 + distance2, point[0]); + Assert.assertEquals(distance1 + distance2, point[0], 0.01); } /** - * Tests the logic to get the values of time in {@link ChartFragment#fillDataPoint(Location, - * double[])}. + * Tests the logic to get the values of time in {@link ChartFragment#fillDataPoint(Location, double[])}. */ + @Test public void testFillDataPoint_time() { // By time chartFragment.setChartByDistance(false); SensorDataSetLocation sensorDataSetLocation1 = TrackStubUtils.createSensorDataSetLocation(); double[] point = fillDataPointTestHelper(sensorDataSetLocation1); - Assert.assertEquals(0.0, point[0]); + Assert.assertEquals(0.0, point[0], 0.01); long timeSpan = 222; SensorDataSetLocation sensorDataSetLocation2 = TrackStubUtils.createSensorDataSetLocation(); sensorDataSetLocation2.setTime(sensorDataSetLocation1.getTime() + timeSpan); point = fillDataPointTestHelper(sensorDataSetLocation2); - Assert.assertEquals((double) timeSpan, point[0]); + Assert.assertEquals((double) timeSpan, point[0], 0.01); } /** - * Tests the logic to get the value of elevation in {@link ChartFragment#fillDataPoint(Location, - * double[])} by one and two points. + * Tests the logic to get the value of elevation in {@link ChartFragment#fillDataPoint(Location, double[])} by one and two points. */ + @Test public void testFillDataPoint_elevation() { SensorDataSetLocation sensorDataSetLocation1 = TrackStubUtils.createSensorDataSetLocation(); @@ -232,7 +214,7 @@ public class ChartFragmentTest { * parameter. Then only one value INITIALLONGTITUDE in buffer. */ double[] point = fillDataPointTestHelper(sensorDataSetLocation1); - Assert.assertEquals(TrackStubUtils.INITIAL_ALTITUDE, point[ChartView.ELEVATION_SERIES + 1]); + Assert.assertEquals(TrackStubUtils.INITIAL_ALTITUDE, point[ChartView.ELEVATION_SERIES + 1], 0.01); /* * Send another value to buffer, now there are two values, INITIALALTITUDE @@ -242,15 +224,15 @@ public class ChartFragmentTest { sensorDataSetLocation2.setAltitude(TrackStubUtils.INITIAL_ALTITUDE * 2); point = fillDataPointTestHelper(sensorDataSetLocation2); Assert.assertEquals((TrackStubUtils.INITIAL_ALTITUDE + TrackStubUtils.INITIAL_ALTITUDE * 2) / 2.0, - point[ChartView.ELEVATION_SERIES + 1]); + point[ChartView.ELEVATION_SERIES + 1], 0.01); } /** - * Tests the logic to get the value of speed in {@link ChartFragment#fillDataPoint(Location, - * double[])}. In this test, firstly remove all - * points in memory, and then fill in two points one by one. The speed values - * of these points are 129, 130. + * Tests the logic to get the value of speed in {@link ChartFragment#fillDataPoint(Location, double[])}. + * In this test, firstly remove all points in memory, and then fill in two points one by one. + * The speed values of these points are 129, 130. */ + @Test public void testFillDataPoint_speed() { /* * At first, clear old points of speed, so give true to the second @@ -259,7 +241,7 @@ public class ChartFragmentTest { SensorDataSetLocation sensorDataSetLocation1 = TrackStubUtils.createSensorDataSetLocation(); sensorDataSetLocation1.setSpeed(128.5f); double[] point = fillDataPointTestHelper(sensorDataSetLocation1); - Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1]); + Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1], 0.01); /* * Tests the logic when both metricUnits and reportSpeed are true.This @@ -274,12 +256,13 @@ public class ChartFragmentTest { sensorDataSetLocation2.setTime(sensorDataSetLocation1.getTime() + 222); sensorDataSetLocation2.setSpeed(130); point = fillDataPointTestHelper(sensorDataSetLocation2); - Assert.assertEquals(130.0 * UnitConversions.MS_TO_KMH, point[ChartView.SPEED_SERIES + 1]); + Assert.assertEquals(130.0 * UnitConversions.MS_TO_KMH, point[ChartView.SPEED_SERIES + 1], 0.01); } /** * Tests the logic to compute speed when use Imperial. */ + @Test public void testFillDataPoint_speedImperial() { // Setups to use imperial. chartFragment.setMetricUnits(false); @@ -288,7 +271,7 @@ public class ChartFragmentTest { SensorDataSetLocation sensorDataSetLocation1 = TrackStubUtils.createSensorDataSetLocation(); sensorDataSetLocation1.setSpeed(100.0f); double[] point = fillDataPointTestHelper(sensorDataSetLocation1); - Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1]); + Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1], 0.01); SensorDataSetLocation sensorDataSetLocation2 = TrackStubUtils.createSensorDataSetLocation(); @@ -300,12 +283,13 @@ public class ChartFragmentTest { sensorDataSetLocation2.setTime(sensorDataSetLocation2.getTime() + 222); sensorDataSetLocation2.setSpeed(102); point = fillDataPointTestHelper(sensorDataSetLocation2); - Assert.assertEquals(102.0 * UnitConversions.MS_TO_KMH * UnitConversions.KM_TO_MI, point[ChartView.SPEED_SERIES + 1]); + Assert.assertEquals(102.0 * UnitConversions.MS_TO_KMH * UnitConversions.KM_TO_MI, point[ChartView.SPEED_SERIES + 1], 0.01); } /** * Tests the logic to get pace value when reportSpeed is false. */ + @Test public void testFillDataPoint_pace_nonZeroSpeed() { // Setups reportSpeed to false. chartFragment.setReportSpeed(false); @@ -314,7 +298,7 @@ public class ChartFragmentTest { SensorDataSetLocation sensorDataSetLocation1 = TrackStubUtils.createSensorDataSetLocation(); sensorDataSetLocation1.setSpeed(100.0f); double[] point = fillDataPointTestHelper(sensorDataSetLocation1); - Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1]); + Assert.assertEquals(0.0, point[ChartView.SPEED_SERIES + 1], 0.01); SensorDataSetLocation sensorDataSetLocation2 = TrackStubUtils.createSensorDataSetLocation(); @@ -326,20 +310,21 @@ public class ChartFragmentTest { sensorDataSetLocation2.setTime(sensorDataSetLocation2.getTime() + 222); sensorDataSetLocation2.setSpeed(102); point = fillDataPointTestHelper(sensorDataSetLocation2); - Assert.assertEquals(HOURS_PER_UNIT / (102.0 * UnitConversions.MS_TO_KMH), point[ChartView.PACE_SERIES + 1]); + Assert.assertEquals(HOURS_PER_UNIT / (102.0 * UnitConversions.MS_TO_KMH), point[ChartView.PACE_SERIES + 1], 0.01); } /** * Tests the logic to get pace value when reportSpeed is false and average * speed is zero. */ + @Test public void testFillDataPoint_pace_zeroSpeed() { // Setups reportSpeed to false. chartFragment.setReportSpeed(false); SensorDataSetLocation sensorDataSetLocation = TrackStubUtils.createSensorDataSetLocation(); sensorDataSetLocation.setSpeed(0); double[] point = fillDataPointTestHelper(sensorDataSetLocation); - Assert.assertEquals(0.0, point[ChartView.PACE_SERIES + 1]); + Assert.assertEquals(0.0, point[ChartView.PACE_SERIES + 1], 0.01); } /** @@ -353,5 +338,4 @@ public class ChartFragmentTest { chartFragment.fillDataPoint(location, point); return point; } - } diff --git a/src/androidTest/java/de/dennisguse/opentracks/services/ControlRecordingServiceTest.java b/src/androidTest/java/de/dennisguse/opentracks/services/ControlRecordingServiceTest.java index 532b58892..4aff9d520 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/services/ControlRecordingServiceTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/services/ControlRecordingServiceTest.java @@ -17,55 +17,52 @@ package de.dennisguse.opentracks.services; import android.content.Context; import android.content.Intent; -import android.os.RemoteException; -import android.test.ServiceTestCase; + +import androidx.test.core.app.ApplicationProvider; +import androidx.test.rule.ServiceTestRule; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; + +import java.util.concurrent.TimeoutException; import de.dennisguse.opentracks.R; -import com.google.android.testing.mocking.UsesMocks; -import org.easymock.EasyMock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * Tests {@link ControlRecordingService}. * * @author Youtao Liu */ -public class ControlRecordingServiceTest extends ServiceTestCase { +public class ControlRecordingServiceTest { - private Context context; - private ControlRecordingService controlRecordingService; + @Rule + public final ServiceTestRule mServiceRule = new ServiceTestRule(); + private Context context = ApplicationProvider.getApplicationContext(); + @Mock + private ITrackRecordingService iTrackRecordingServiceMock; - public ControlRecordingServiceTest() { - super(ControlRecordingService.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - context = getContext(); - } + private ControlRecordingService subject; /** * Tests the start of {@link ControlRecordingService} and tests the method * {@link ControlRecordingService#onHandleIntent(Intent, ITrackRecordingService)} * to start a track recording. */ - @UsesMocks(ITrackRecordingService.class) - public void testStartRecording() { - assertNull(controlRecordingService); + @Test + public void testStartRecording() throws TimeoutException { + Assert.assertNull(subject); Intent intent = startControlRecordingService(context.getString(R.string.track_action_start)); - assertNotNull(controlRecordingService); + Assert.assertNotNull(subject); - ITrackRecordingService iTrackRecordingServiceMock = EasyMock - .createStrictMock(ITrackRecordingService.class); - try { - EasyMock.expect(iTrackRecordingServiceMock.startNewTrack()).andReturn(1L); - EasyMock.replay(iTrackRecordingServiceMock); - controlRecordingService.onHandleIntent(intent, iTrackRecordingServiceMock); - EasyMock.verify(iTrackRecordingServiceMock); - } catch (RemoteException e) { - fail(); - } + when(iTrackRecordingServiceMock.startNewTrack()).thenReturn(1L); + subject.onHandleIntent(intent, iTrackRecordingServiceMock); + verify(iTrackRecordingServiceMock); } /** @@ -73,20 +70,13 @@ public class ControlRecordingServiceTest extends ServiceTestCase - * TODO: The original class, ServiceTestCase, has a few limitations, e.g. it's - * not possible to properly shutdown the service, unless tearDown() is called, - * which prevents from testing multiple scenarios in a single test (see - * runFunctionTest for more details). * * @author Bartlomiej Niechwiej */ -public class TrackRecordingServiceTest extends ServiceTestCase { +@RunWith(AndroidJUnit4.class) +public class TrackRecordingServiceTest { - private Context context; + @Rule + public final ServiceTestRule mServiceRule = new ServiceTestRule(); private ContentProviderUtils providerUtils; + private Context context = ApplicationProvider.getApplicationContext(); - /* - * In order to support starting and binding to the service in the same unit - * test, we provide a workaround, as the original class doesn't allow to bind - * after the service has been previously started. - */ - - private boolean bound; - private Intent serviceIntent; - - public TrackRecordingServiceTest() { - super(TestRecordingService.class); - } - - @Override - protected IBinder bindService(Intent intent) { - if (getService() != null) { - if (bound) { - throw new IllegalStateException("Service: " + getService() + " is already bound"); - } - bound = true; - serviceIntent = intent.cloneFilter(); - return getService().onBind(intent); - } else { - return super.bindService(intent); - } - } - - @Override - protected void shutdownService() { - if (bound) { - assertNotNull(getService()); - getService().onUnbind(serviceIntent); - bound = false; - } - super.shutdownService(); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - /* - * Create a mock context that uses a mock content resolver and a renaming - * delegating context. - */ - MockContentResolver mockContentResolver = new MockContentResolver(); - RenamingDelegatingContext renamingDelegatingContext = new RenamingDelegatingContext( - getContext(), getContext(), "test."); - context = new MockContext(mockContentResolver, renamingDelegatingContext); - + @Before + public void setUp() throws Exception { // Set up the mock content resolver CustomContentProvider customContentProvider = new CustomContentProvider(); customContentProvider.attachInfo(context, null); - mockContentResolver.addProvider(ContentProviderUtils.AUTHORITY, customContentProvider); - - MockContentProvider settingsProvider = new MockContentProvider(context) { - @Override - public Bundle call(String method, String arg, Bundle extras) { - return null; - } - - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { - return null; - } - }; - mockContentResolver.addProvider(Settings.AUTHORITY, settingsProvider); - - // Set the context - setContext(context); providerUtils = ContentProviderUtils.Factory.get(context); @@ -147,20 +78,21 @@ public class TrackRecordingServiceTest extends ServiceTestCase tracks = providerUtils.getAllTracks(); - assertTrue(tracks.isEmpty()); + Assert.assertTrue(tracks.isEmpty()); - ITrackRecordingService service = bindAndGetService(createStartIntent()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); // Test if we start in no-recording mode by default. - assertFalse(service.isRecording()); - assertEquals(-1L, service.getRecordingTrackId()); + Assert.assertFalse(service.isRecording()); + Assert.assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest public void testRecording_oldTracks() throws Exception { createDummyTrack(123L, -1L, false); - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertFalse(service.isRecording()); - assertEquals(-1L, service.getRecordingTrackId()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertFalse(service.isRecording()); + Assert.assertEquals(-1L, service.getRecordingTrackId()); } @MediumTest @@ -305,9 +225,9 @@ public class TrackRecordingServiceTest extends ServiceTestCase tracks = providerUtils.getAllTracks(); - assertTrue(tracks.isEmpty()); + Assert.assertTrue(tracks.isEmpty()); - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertFalse(service.isRecording()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertFalse(service.isRecording()); long id = service.startNewTrack(); - assertTrue(id >= 0); - assertTrue(service.isRecording()); + Assert.assertTrue(id >= 0); + Assert.assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); - assertNotNull(track); - assertEquals(id, track.getId()); - assertEquals(PreferencesUtils.getString( - context, R.string.default_activity_key, PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT), - track.getCategory()); - assertEquals(id, PreferencesUtils.getLong(context, R.string.recording_track_id_key)); - assertEquals(id, service.getRecordingTrackId()); + Assert.assertNotNull(track); + Assert.assertEquals(id, track.getId()); + Assert.assertEquals(PreferencesUtils.getString(context, R.string.default_activity_key, PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT), track.getCategory()); + Assert.assertEquals(id, PreferencesUtils.getLong(context, R.string.recording_track_id_key)); + Assert.assertEquals(id, service.getRecordingTrackId()); // Verify that the start broadcast was received. - assertTrue(startReceiver.waitUntilReceived(1)); + Assert.assertTrue(startReceiver.waitUntilReceived(1)); List receivedIntents = startReceiver.getReceivedIntents(); - assertEquals(1, receivedIntents.size()); + Assert.assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); - assertEquals(startAction, broadcastIntent.getAction()); - assertEquals(id, - broadcastIntent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L)); + Assert.assertEquals(startAction, broadcastIntent.getAction()); + Assert.assertEquals(id, broadcastIntent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L)); context.unregisterReceiver(startReceiver); } @@ -353,15 +270,15 @@ public class TrackRecordingServiceTest extends ServiceTestCase receivedIntents = stopReceiver.getReceivedIntents(); - assertEquals(1, receivedIntents.size()); + Assert.assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); - assertEquals(stopAction, broadcastIntent.getAction()); - assertEquals(123L, - broadcastIntent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L)); + Assert.assertEquals(stopAction, broadcastIntent.getAction()); + Assert.assertEquals(123L, broadcastIntent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L)); context.unregisterReceiver(stopReceiver); } @MediumTest public void testEndCurrentTrack_noRecording() throws Exception { - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertFalse(service.isRecording()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertFalse(service.isRecording()); /* * Ending the current track when there is no recording should not result in @@ -406,47 +321,47 @@ public class TrackRecordingServiceTest extends ServiceTestCase tracks = providerUtils.getAllTracks(); - assertTrue(tracks.isEmpty()); + Assert.assertTrue(tracks.isEmpty()); fullRecordingSession(); } @MediumTest public void testInsertStatisticsMarker_noRecordingTrack() throws Exception { - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertFalse(service.isRecording()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertFalse(service.isRecording()); long waypointId = service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); - assertEquals(-1L, waypointId); + Assert.assertEquals(-1L, waypointId); } @MediumTest public void testInsertStatisticsMarker_validLocation() throws Exception { createDummyTrack(123L, -1L, true); - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertTrue(service.isRecording()); - assertFalse(service.isPaused()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertTrue(service.isRecording()); + Assert.assertFalse(service.isPaused()); insertLocation(service); - assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); - assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); + Assert.assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); + Assert.assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); Waypoint wpt = providerUtils.getWaypoint(2); - assertEquals(getContext().getString(R.string.marker_statistics_icon_url), wpt.getIcon()); - assertEquals(getContext().getString(R.string.marker_split_name_format, 1), wpt.getName()); - assertEquals(WaypointType.STATISTICS, wpt.getType()); - assertEquals(123L, wpt.getTrackId()); - assertEquals(0.0, wpt.getLength()); - assertNotNull(wpt.getLocation()); - assertNotNull(wpt.getTripStatistics()); + Assert.assertEquals(context.getString(R.string.marker_statistics_icon_url), wpt.getIcon()); + Assert.assertEquals(context.getString(R.string.marker_split_name_format, 1), wpt.getName()); + Assert.assertEquals(WaypointType.STATISTICS, wpt.getType()); + Assert.assertEquals(123L, wpt.getTrackId()); + Assert.assertEquals(0.0, wpt.getLength()); + Assert.assertNotNull(wpt.getLocation()); + Assert.assertNotNull(wpt.getTripStatistics()); // TODO check the rest of the params. // TODO: Check waypoint 2. @@ -454,36 +369,35 @@ public class TrackRecordingServiceTest extends ServiceTestCase= 0); + Assert.assertTrue(track.getId() >= 0); providerUtils.insertTrack(track); - assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); - PreferencesUtils.setLong(context, R.string.recording_track_id_key, - isRecording ? track.getId() : PreferencesUtils.RECORDING_TRACK_ID_DEFAULT); + Assert.assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); + PreferencesUtils.setLong(context, R.string.recording_track_id_key, isRecording ? track.getId() : PreferencesUtils.RECORDING_TRACK_ID_DEFAULT); PreferencesUtils.setBoolean(context, R.string.recording_track_paused_key, !isRecording); } private void fullRecordingSession() throws Exception { - ITrackRecordingService service = bindAndGetService(createStartIntent()); - assertFalse(service.isRecording()); + ITrackRecordingService service = ((ITrackRecordingService) mServiceRule.bindService(createStartIntent())); + Assert.assertFalse(service.isRecording()); // Start a track. long id = service.startNewTrack(); - assertTrue(id >= 0); - assertTrue(service.isRecording()); + Assert.assertTrue(id >= 0); + Assert.assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); - assertNotNull(track); - assertEquals(id, track.getId()); - assertEquals(id, PreferencesUtils.getLong(context, R.string.recording_track_id_key)); - assertEquals(id, service.getRecordingTrackId()); + Assert.assertNotNull(track); + Assert.assertEquals(id, track.getId()); + Assert.assertEquals(id, PreferencesUtils.getLong(context, R.string.recording_track_id_key)); + Assert.assertEquals(id, service.getRecordingTrackId()); // Insert a few points, markers and statistics. long startTime = System.currentTimeMillis(); @@ -670,15 +556,15 @@ public class TrackRecordingServiceTest extends ServiceTestCase 0); - assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime()); + Assert.assertNotNull(tripStatistics); + Assert.assertTrue(tripStatistics.getStartTime() > 0); + Assert.assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime()); } /** @@ -686,8 +572,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase receivedIntents = new ArrayList(); + private final List receivedIntents = new ArrayList<>(); public List getReceivedIntents() { return receivedIntents; diff --git a/src/androidTest/java/de/dennisguse/opentracks/util/TrackNameUtilsTest.java b/src/androidTest/java/de/dennisguse/opentracks/util/TrackNameUtilsTest.java index f38c4f67e..8002841ea 100644 --- a/src/androidTest/java/de/dennisguse/opentracks/util/TrackNameUtilsTest.java +++ b/src/androidTest/java/de/dennisguse/opentracks/util/TrackNameUtilsTest.java @@ -21,8 +21,6 @@ import android.content.Context; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; -import de.dennisguse.opentracks.R; - import org.junit.Assert; import org.junit.runner.RunWith; @@ -30,6 +28,8 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import de.dennisguse.opentracks.R; + /** * Tests {@link TrackNameUtils}. * @@ -49,8 +49,7 @@ public class TrackNameUtilsTest { */ public void testTrackName_date_local() { PreferencesUtils.setString(CONTEXT, R.string.track_name_key, CONTEXT.getString(R.string.settings_recording_track_name_date_local_value)); - Assert.assertEquals(StringUtils.formatDateTime(CONTEXT, START_TIME), - TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME, null)); + Assert.assertEquals(StringUtils.formatDateTime(CONTEXT, START_TIME), TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME)); } /** @@ -59,10 +58,8 @@ public class TrackNameUtilsTest { */ public void testTrackName_date_iso_8601() { PreferencesUtils.setString(CONTEXT, R.string.track_name_key, CONTEXT.getString(R.string.settings_recording_track_name_date_iso_8601_value)); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat( - TrackNameUtils.ISO_8601_FORMAT, Locale.US); - Assert.assertEquals(simpleDateFormat.format(new Date(START_TIME)), - TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME, null)); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TrackNameUtils.ISO_8601_FORMAT, Locale.US); + Assert.assertEquals(simpleDateFormat.format(new Date(START_TIME)), TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME)); } /** @@ -71,7 +68,6 @@ public class TrackNameUtilsTest { */ public void testTrackName_number() { PreferencesUtils.setString(CONTEXT, R.string.track_name_key, CONTEXT.getString(R.string.settings_recording_track_name_number_value)); - Assert.assertEquals( - "Track " + TRACK_ID, TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME, null)); + Assert.assertEquals("Track " + TRACK_ID, TrackNameUtils.getTrackName(CONTEXT, TRACK_ID, START_TIME)); } } diff --git a/src/main/java/de/dennisguse/opentracks/content/ContentProviderUtils.java b/src/main/java/de/dennisguse/opentracks/content/ContentProviderUtils.java index 998207fd2..d3f48add6 100644 --- a/src/main/java/de/dennisguse/opentracks/content/ContentProviderUtils.java +++ b/src/main/java/de/dennisguse/opentracks/content/ContentProviderUtils.java @@ -22,12 +22,12 @@ import android.location.Location; import android.location.LocationManager; import android.net.Uri; -import de.dennisguse.opentracks.BuildConfig; -import de.dennisguse.opentracks.content.Waypoint.WaypointType; - import java.util.Iterator; import java.util.List; +import de.dennisguse.opentracks.BuildConfig; +import de.dennisguse.opentracks.content.Waypoint.WaypointType; + /** * Utilities to access data from the app's content provider. * @@ -354,8 +354,7 @@ public interface ContentProviderUtils { } /** - * A factory which can produce instances of {@link ContentProviderUtils}, and - * can be overridden for testing. + * A factory which can produce instances of {@link ContentProviderUtils}, and can be overridden for testing. */ class Factory { diff --git a/src/main/java/de/dennisguse/opentracks/services/TrackRecordingService.java b/src/main/java/de/dennisguse/opentracks/services/TrackRecordingService.java index a48536a8f..ab734c99f 100644 --- a/src/main/java/de/dennisguse/opentracks/services/TrackRecordingService.java +++ b/src/main/java/de/dennisguse/opentracks/services/TrackRecordingService.java @@ -41,7 +41,10 @@ import androidx.annotation.VisibleForTesting; import androidx.core.app.NotificationCompat; import androidx.core.app.TaskStackBuilder; -import de.dennisguse.opentracks.Constants; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import de.dennisguse.opentracks.R; import de.dennisguse.opentracks.TrackDetailActivity; import de.dennisguse.opentracks.TrackListActivity; import de.dennisguse.opentracks.content.ContentProviderUtils; @@ -69,10 +72,6 @@ import de.dennisguse.opentracks.util.SystemUtils; import de.dennisguse.opentracks.util.TrackIconUtils; import de.dennisguse.opentracks.util.TrackNameUtils; import de.dennisguse.opentracks.util.UnitConversions; -import de.dennisguse.opentracks.R; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; /** * A background service that registers a location listener and records track @@ -1013,8 +1012,7 @@ public class TrackRecordingService extends Service { * @param trackId the track id */ private void sendTrackBroadcast(int actionId, long trackId) { - Intent intent = new Intent().setAction(getString(actionId)) - .putExtra(getString(R.string.track_id_broadcast_extra), trackId); + Intent intent = new Intent().setAction(getString(actionId)).putExtra(getString(R.string.track_id_broadcast_extra), trackId); sendBroadcast(intent, getString(R.string.permission_notification_value)); }