@@ -9,7 +9,10 @@ import io.sentry.android.core.SentryAndroidOptions
99import io.sentry.android.core.SentryShadowProcess
1010import org.junit.Before
1111import org.junit.runner.RunWith
12+ import org.mockito.kotlin.eq
1213import org.mockito.kotlin.mock
14+ import org.mockito.kotlin.never
15+ import org.mockito.kotlin.verify
1316import org.robolectric.Shadows
1417import org.robolectric.annotation.Config
1518import java.util.concurrent.TimeUnit
@@ -201,4 +204,45 @@ class AppStartMetricsTest {
201204 val timeSpan = AppStartMetrics .getInstance().getAppStartTimeSpanWithFallback(options)
202205 assertFalse(timeSpan.hasStarted())
203206 }
207+
208+ @Test
209+ fun `when registerApplicationForegroundCheck, a callback is registered to application` () {
210+ val application = mock<Application >()
211+ AppStartMetrics .getInstance().registerApplicationForegroundCheck(application)
212+ verify(application).registerActivityLifecycleCallbacks(eq(AppStartMetrics .getInstance()))
213+ }
214+
215+ @Test
216+ fun `when registerApplicationForegroundCheck, a job is posted on main thread to unregistered the callback` () {
217+ val application = mock<Application >()
218+ AppStartMetrics .getInstance().registerApplicationForegroundCheck(application)
219+ verify(application).registerActivityLifecycleCallbacks(eq(AppStartMetrics .getInstance()))
220+ verify(application, never()).unregisterActivityLifecycleCallbacks(eq(AppStartMetrics .getInstance()))
221+ Shadows .shadowOf(Looper .getMainLooper()).idle()
222+ verify(application).unregisterActivityLifecycleCallbacks(eq(AppStartMetrics .getInstance()))
223+ }
224+
225+ @Test
226+ fun `registerApplicationForegroundCheck set foreground state to false if no activity is running` () {
227+ val application = mock<Application >()
228+ AppStartMetrics .getInstance().isAppLaunchedInForeground = true
229+ AppStartMetrics .getInstance().registerApplicationForegroundCheck(application)
230+ assertTrue(AppStartMetrics .getInstance().isAppLaunchedInForeground)
231+ // Main thread performs the check and sets the flag to false if no activity was created
232+ Shadows .shadowOf(Looper .getMainLooper()).idle()
233+ assertFalse(AppStartMetrics .getInstance().isAppLaunchedInForeground)
234+ }
235+
236+ @Test
237+ fun `registerApplicationForegroundCheck keeps foreground state to true if an activity is running` () {
238+ val application = mock<Application >()
239+ AppStartMetrics .getInstance().isAppLaunchedInForeground = true
240+ AppStartMetrics .getInstance().registerApplicationForegroundCheck(application)
241+ assertTrue(AppStartMetrics .getInstance().isAppLaunchedInForeground)
242+ // An activity was created
243+ AppStartMetrics .getInstance().onActivityCreated(mock(), null )
244+ // Main thread performs the check and keeps the flag to true
245+ Shadows .shadowOf(Looper .getMainLooper()).idle()
246+ assertTrue(AppStartMetrics .getInstance().isAppLaunchedInForeground)
247+ }
204248}
0 commit comments