[fenix] For https://github.com/mozilla-mobile/fenix/issues/23876 - Update kotlinx-coroutines to 1.6.1. Refactor runBlocking in tests.

After the update `TestCoroutineDispatcher`, `TestCoroutineScope` and
`runBlockingTest` are deprecated.
Instead of these new `TestDispatcher`, `TestScope` and `runTest` APIs are used.

Took the oportunity to also replace most of the `runBlocking` calls with the
new `runTest` specially designed for running coroutines in tests API.
pull/600/head
Mugurell 2 years ago committed by Christian Sadilek
parent f14b746b89
commit c6bb6c247e

@ -18,7 +18,7 @@ import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkStatic
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.feature.intent.processing.IntentProcessor
import mozilla.components.support.test.robolectric.testContext
import mozilla.telemetry.glean.testing.GleanTestRule
@ -77,7 +77,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent with flag launched from history`() = runBlockingTest {
fun `process intent with flag launched from history`() = runTest {
val intent = Intent()
intent.flags = FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
assertFalse(Events.openedLink.testHasValue())
@ -96,7 +96,7 @@ class IntentReceiverActivityTest {
@Test
fun `GIVEN a deeplink intent WHEN processing the intent THEN add the className HomeActivity`() =
runBlockingTest {
runTest {
val uri = Uri.parse(BuildConfig.DEEP_LINK_SCHEME + "://settings_wallpapers")
val intent = Intent("", uri)
assertFalse(Events.openedLink.testHasValue())
@ -117,7 +117,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent with action OPEN_PRIVATE_TAB`() = runBlockingTest {
fun `process intent with action OPEN_PRIVATE_TAB`() = runTest {
val intent = Intent()
intent.action = NewTabShortcutIntentProcessor.ACTION_OPEN_PRIVATE_TAB
assertFalse(Events.openedLink.testHasValue())
@ -138,7 +138,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent with action OPEN_TAB`() = runBlockingTest {
fun `process intent with action OPEN_TAB`() = runTest {
assertFalse(Events.openedLink.testHasValue())
val intent = Intent()
intent.action = NewTabShortcutIntentProcessor.ACTION_OPEN_TAB
@ -156,7 +156,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent starts Activity`() = runBlockingTest {
fun `process intent starts Activity`() = runTest {
assertFalse(Events.openedLink.testHasValue())
val intent = Intent()
val activity = Robolectric.buildActivity(IntentReceiverActivity::class.java, intent).get()
@ -172,7 +172,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent with launchLinksInPrivateTab set to true`() = runBlockingTest {
fun `process intent with launchLinksInPrivateTab set to true`() = runTest {
assertFalse(Events.openedLink.testHasValue())
every { settings.openLinksInAPrivateTab } returns true
@ -197,7 +197,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process intent with launchLinksInPrivateTab set to false`() = runBlockingTest {
fun `process intent with launchLinksInPrivateTab set to false`() = runTest {
assertFalse(Events.openedLink.testHasValue())
val intent = Intent()
@ -211,7 +211,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process custom tab intent`() = runBlockingTest {
fun `process custom tab intent`() = runTest {
assertFalse(Events.openedLink.testHasValue())
val intent = Intent()
coEvery { intentProcessors.intentProcessor.process(intent) } returns false
@ -231,7 +231,7 @@ class IntentReceiverActivityTest {
}
@Test
fun `process private custom tab intent`() = runBlockingTest {
fun `process private custom tab intent`() = runTest {
assertFalse(Events.openedLink.testHasValue())
every { settings.openLinksInAPrivateTab } returns true

@ -11,8 +11,7 @@ import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.state.action.TabListAction
import mozilla.components.browser.state.state.createTab
import mozilla.components.browser.state.store.BrowserStore
@ -20,7 +19,8 @@ import mozilla.components.feature.tab.collections.TabCollection
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.ext.joinBlocking
import mozilla.components.support.test.robolectric.testContext
import org.junit.After
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
@ -39,7 +39,10 @@ class DefaultCollectionCreationControllerTest {
@get:Rule
val gleanTestRule = GleanTestRule(testContext)
private val testCoroutineScope = TestCoroutineScope()
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val scope = coroutinesTestRule.scope
private lateinit var state: CollectionCreationState
private lateinit var controller: DefaultCollectionCreationController
private var dismissed = false
@ -68,15 +71,10 @@ class DefaultCollectionCreationControllerTest {
dismissed = true
},
tabCollectionStorage,
testCoroutineScope
scope
)
}
@After
fun cleanUp() {
testCoroutineScope.cleanupTestCoroutines()
}
@Test
fun `GIVEN tab list WHEN saveCollectionName is called THEN collection should be created`() {
val tab1 = createTab("https://www.mozilla.org", id = "session-1")
@ -146,7 +144,7 @@ class DefaultCollectionCreationControllerTest {
}
@Test
fun `GIVEN collection WHEN renameCollection is called THEN collection should be renamed`() = testCoroutineScope.runBlockingTest {
fun `GIVEN collection WHEN renameCollection is called THEN collection should be renamed`() = runTestOnMain {
val collection = mockk<TabCollection>()
controller.renameCollection(collection, "name")

@ -9,7 +9,7 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.mozilla.fenix.helpers.FenixRobolectricTestRunner
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.lib.crash.CrashReporter
import mozilla.components.service.fxa.manager.FxaAccountManager
import mozilla.components.support.test.robolectric.testContext
@ -54,7 +54,7 @@ class AccountAbnormalitiesTest {
}
@Test
fun `LogoutWithoutAuth detected`() = runBlocking {
fun `LogoutWithoutAuth detected`() = runTest {
val crashReporter: CrashReporter = mockk(relaxed = true)
val accountAbnormalities = AccountAbnormalities(
@ -70,7 +70,7 @@ class AccountAbnormalitiesTest {
}
@Test
fun `OverlappingFxaLogoutRequest detected`() = runBlocking {
fun `OverlappingFxaLogoutRequest detected`() = runTest {
val crashReporter: CrashReporter = mockk(relaxed = true)
val accountAbnormalities = AccountAbnormalities(
@ -91,7 +91,7 @@ class AccountAbnormalitiesTest {
}
@Test
fun `callback logout abnormalities detected`() = runBlocking {
fun `callback logout abnormalities detected`() = runTest {
val crashReporter: CrashReporter = mockk(relaxed = true)
val accountAbnormalities = AccountAbnormalities(
@ -107,7 +107,7 @@ class AccountAbnormalitiesTest {
}
@Test
fun `login happy case + disappearing account detected`() = runBlocking {
fun `login happy case + disappearing account detected`() = runTest {
val crashReporter: CrashReporter = mockk(relaxed = true)
val accountManager: FxaAccountManager = mockk(relaxed = true)
@ -136,7 +136,7 @@ class AccountAbnormalitiesTest {
}
@Test
fun `logout happy case`() = runBlocking {
fun `logout happy case`() = runTest {
val crashReporter: CrashReporter = mockk()
val accountAbnormalities = AccountAbnormalities(

@ -9,7 +9,7 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.sync.DeviceType
import mozilla.components.feature.tab.collections.TabCollection
import mozilla.components.feature.top.sites.TopSite
@ -84,7 +84,7 @@ class AppStoreTest {
}
@Test
fun `Test toggling the mode in AppStore`() = runBlocking {
fun `Test toggling the mode in AppStore`() = runTest {
// Verify that the default mode and tab states of the HomeFragment are correct.
assertEquals(Mode.Normal, appStore.state.mode)
@ -99,7 +99,7 @@ class AppStoreTest {
@Test
fun `GIVEN a new value for messageToShow WHEN NimbusMessageChange is called THEN update the current value`() =
runBlocking {
runTest {
assertNull(appStore.state.messaging.messageToShow)
appStore.dispatch(UpdateMessageToShow(mockk())).join()
@ -108,7 +108,7 @@ class AppStoreTest {
}
@Test
fun `Test changing the collections in AppStore`() = runBlocking {
fun `Test changing the collections in AppStore`() = runTest {
assertEquals(0, appStore.state.collections.size)
// Add 2 TabCollections to the AppStore.
@ -119,7 +119,7 @@ class AppStoreTest {
}
@Test
fun `Test changing the top sites in AppStore`() = runBlocking {
fun `Test changing the top sites in AppStore`() = runTest {
assertEquals(0, appStore.state.topSites.size)
// Add 2 TopSites to the AppStore.
@ -130,7 +130,7 @@ class AppStoreTest {
}
@Test
fun `Test changing the recent tabs in AppStore`() = runBlocking {
fun `Test changing the recent tabs in AppStore`() = runTest {
val group1 = RecentHistoryGroup(title = "title1")
val group2 = RecentHistoryGroup(title = "title2")
val group3 = RecentHistoryGroup(title = "title3")
@ -154,7 +154,7 @@ class AppStoreTest {
}
@Test
fun `GIVEN initial state WHEN recent synced tab state is changed THEN state updated`() = runBlocking {
fun `GIVEN initial state WHEN recent synced tab state is changed THEN state updated`() = runTest {
appStore = AppStore(
AppState(
recentSyncedTabState = RecentSyncedTabState.None
@ -173,7 +173,7 @@ class AppStoreTest {
}
@Test
fun `Test changing the history metadata in AppStore`() = runBlocking {
fun `Test changing the history metadata in AppStore`() = runTest {
assertEquals(0, appStore.state.recentHistory.size)
val historyMetadata: List<RecentHistoryGroup> = listOf(mockk(), mockk())
@ -183,7 +183,7 @@ class AppStoreTest {
}
@Test
fun `Test removing a history highlight from AppStore`() = runBlocking {
fun `Test removing a history highlight from AppStore`() = runTest {
val g1 = RecentHistoryGroup(title = "group One")
val g2 = RecentHistoryGroup(title = "grup two")
val h1 = RecentHistoryHighlight(title = "highlight One", url = "url1")
@ -207,7 +207,7 @@ class AppStoreTest {
}
@Test
fun `Test disbanding search group in AppStore`() = runBlocking {
fun `Test disbanding search group in AppStore`() = runTest {
val g1 = RecentHistoryGroup(title = "test One")
val g2 = RecentHistoryGroup(title = "test two")
val h1 = RecentHistoryHighlight(title = "highlight One", url = "url1")
@ -221,7 +221,7 @@ class AppStoreTest {
}
@Test
fun `Test changing hiding collections placeholder`() = runBlocking {
fun `Test changing hiding collections placeholder`() = runTest {
assertTrue(appStore.state.showCollectionPlaceholder)
appStore.dispatch(AppAction.RemoveCollectionsPlaceholder).join()
@ -230,7 +230,7 @@ class AppStoreTest {
}
@Test
fun `Test changing the expanded collections in AppStore`() = runBlocking {
fun `Test changing the expanded collections in AppStore`() = runTest {
val collection: TabCollection = mockk<TabCollection>().apply {
every { id } returns 0
}
@ -245,7 +245,7 @@ class AppStoreTest {
@Test
fun `Test changing the collections, mode, recent tabs and bookmarks, history metadata and top sites in the AppStore`() =
runBlocking {
runTest {
// Verify that the default state of the HomeFragment is correct.
assertEquals(0, appStore.state.collections.size)
assertEquals(0, appStore.state.topSites.size)
@ -286,7 +286,7 @@ class AppStoreTest {
}
@Test
fun `Test selecting a Pocket recommendations category`() = runBlocking {
fun `Test selecting a Pocket recommendations category`() = runTest {
val otherStoriesCategory = PocketRecommendedStoriesCategory("other")
val anotherStoriesCategory = PocketRecommendedStoriesCategory("another")
val filteredStories = listOf(mockk<PocketRecommendedStory>())
@ -314,7 +314,7 @@ class AppStoreTest {
}
@Test
fun `Test deselecting a Pocket recommendations category`() = runBlocking {
fun `Test deselecting a Pocket recommendations category`() = runTest {
val otherStoriesCategory = PocketRecommendedStoriesCategory("other")
val anotherStoriesCategory = PocketRecommendedStoriesCategory("another")
val filteredStories = listOf(mockk<PocketRecommendedStory>())
@ -343,7 +343,7 @@ class AppStoreTest {
}
@Test
fun `Test updating the list of Pocket recommended stories`() = runBlocking {
fun `Test updating the list of Pocket recommended stories`() = runTest {
val story1 = PocketRecommendedStory("title1", "url", "imageUrl", "publisher", "category", 1, 1)
val story2 = story1.copy("title2")
appStore = AppStore(AppState())
@ -358,7 +358,7 @@ class AppStoreTest {
}
@Test
fun `Test updating the list of Pocket recommendations categories`() = runBlocking {
fun `Test updating the list of Pocket recommendations categories`() = runTest {
val otherStoriesCategory = PocketRecommendedStoriesCategory("other")
val anotherStoriesCategory = PocketRecommendedStoriesCategory("another")
appStore = AppStore(AppState())
@ -393,7 +393,7 @@ class AppStoreTest {
}
@Test
fun `Test updating the list of selected Pocket recommendations categories`() = runBlocking {
fun `Test updating the list of selected Pocket recommendations categories`() = runTest {
val otherStoriesCategory = PocketRecommendedStoriesCategory("other")
val anotherStoriesCategory = PocketRecommendedStoriesCategory("another")
val selectedCategory = PocketRecommendedStoriesSelectedCategory("selected")

@ -9,7 +9,7 @@ import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.engine.permission.SitePermissions
import mozilla.components.concept.engine.permission.SitePermissionsStorage
import mozilla.components.support.test.robolectric.testContext
@ -23,7 +23,7 @@ import org.mozilla.fenix.helpers.FenixRobolectricTestRunner
class PermissionStorageTest {
@Test
fun `add permission`() = runBlockingTest {
fun `add permission`() = runTest {
val sitePermissions: SitePermissions = mockk(relaxed = true)
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)
@ -34,7 +34,7 @@ class PermissionStorageTest {
}
@Test
fun `find sitePermissions by origin`() = runBlockingTest {
fun `find sitePermissions by origin`() = runTest {
val sitePermissions: SitePermissions = mockk(relaxed = true)
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)
@ -49,7 +49,7 @@ class PermissionStorageTest {
}
@Test
fun `update SitePermissions`() = runBlockingTest {
fun `update SitePermissions`() = runTest {
val sitePermissions: SitePermissions = mockk(relaxed = true)
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)
@ -60,7 +60,7 @@ class PermissionStorageTest {
}
@Test
fun `get sitePermissions paged`() = runBlockingTest {
fun `get sitePermissions paged`() = runTest {
val dataSource: DataSource.Factory<Int, SitePermissions> = mockk(relaxed = true)
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)
@ -75,7 +75,7 @@ class PermissionStorageTest {
}
@Test
fun `delete sitePermissions`() = runBlockingTest {
fun `delete sitePermissions`() = runTest {
val sitePermissions: SitePermissions = mockk(relaxed = true)
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)
@ -86,7 +86,7 @@ class PermissionStorageTest {
}
@Test
fun `delete all sitePermissions`() = runBlockingTest {
fun `delete all sitePermissions`() = runTest {
val sitePermissionsStorage: SitePermissionsStorage = mockk(relaxed = true)
val storage = PermissionStorage(testContext, this.coroutineContext, sitePermissionsStorage)

@ -6,7 +6,7 @@ package org.mozilla.fenix.components
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.support.test.robolectric.testContext
import org.junit.Test
import org.junit.Assert.assertEquals
@ -37,7 +37,7 @@ class ReviewPromptControllerTest {
}
@Test
fun promptReviewDoesNotSetMillis() = runBlockingTest {
fun promptReviewDoesNotSetMillis() = runTest {
var promptWasCalled = false
val settings = TestReviewSettings(
numberOfAppLaunches = 5,
@ -60,7 +60,7 @@ class ReviewPromptControllerTest {
}
@Test
fun promptReviewSetsMillisIfSuccessful() = runBlockingTest {
fun promptReviewSetsMillisIfSuccessful() = runTest {
var promptWasCalled = false
val settings = TestReviewSettings(
numberOfAppLaunches = 5,
@ -82,7 +82,7 @@ class ReviewPromptControllerTest {
}
@Test
fun promptReviewWillNotBeCalledIfNotReady() = runBlockingTest {
fun promptReviewWillNotBeCalledIfNotReady() = runTest {
var promptWasCalled = false
val settings = TestReviewSettings(
numberOfAppLaunches = 5,
@ -102,7 +102,7 @@ class ReviewPromptControllerTest {
}
@Test
fun promptReviewWillUnreadyPromptAfterCalled() = runBlockingTest {
fun promptReviewWillUnreadyPromptAfterCalled() = runTest {
var promptWasCalled = false
val settings = TestReviewSettings(
numberOfAppLaunches = 5,

@ -8,7 +8,7 @@ import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.appservices.places.BookmarkRoot
import mozilla.components.concept.storage.BookmarkNode
import mozilla.components.concept.storage.BookmarkNodeType
@ -26,7 +26,7 @@ import java.util.concurrent.TimeUnit
class BookmarksUseCaseTest {
@Test
fun `WHEN adding existing bookmark THEN no new item is stored`() = runBlockingTest {
fun `WHEN adding existing bookmark THEN no new item is stored`() = runTest {
val bookmarksStorage = mockk<BookmarksStorage>()
val historyStorage = mockk<HistoryStorage>()
val bookmarkNode = mockk<BookmarkNode>()
@ -41,7 +41,7 @@ class BookmarksUseCaseTest {
}
@Test
fun `WHEN adding bookmark THEN new item is stored`() = runBlockingTest {
fun `WHEN adding bookmark THEN new item is stored`() = runTest {
val bookmarksStorage = mockk<BookmarksStorage>(relaxed = true)
val historyStorage = mockk<HistoryStorage>(relaxed = true)
val useCase = BookmarksUseCase(bookmarksStorage, historyStorage)
@ -56,7 +56,7 @@ class BookmarksUseCaseTest {
}
@Test
fun `WHEN recently saved bookmarks exist THEN retrieve the list from storage`() = runBlockingTest {
fun `WHEN recently saved bookmarks exist THEN retrieve the list from storage`() = runTest {
val bookmarksStorage = mockk<BookmarksStorage>(relaxed = true)
val historyStorage = mockk<HistoryStorage>(relaxed = true)
val useCase = BookmarksUseCase(bookmarksStorage, historyStorage)
@ -115,7 +115,7 @@ class BookmarksUseCaseTest {
}
@Test
fun `WHEN there are no recently saved bookmarks THEN retrieve the empty list from storage`() = runBlockingTest {
fun `WHEN there are no recently saved bookmarks THEN retrieve the empty list from storage`() = runTest {
val bookmarksStorage = mockk<BookmarksStorage>(relaxed = true)
val historyStorage = mockk<HistoryStorage>(relaxed = true)
val useCase = BookmarksUseCase(bookmarksStorage, historyStorage)

@ -7,7 +7,7 @@ package org.mozilla.fenix.components.history
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.storage.sync.PlacesHistoryStorage
import mozilla.components.concept.storage.DocumentType
import mozilla.components.concept.storage.HistoryMetadata
@ -28,7 +28,7 @@ class PagedHistoryProviderTest {
}
@Test
fun `getHistory uses getVisitsPaginated`() = runBlockingTest {
fun `getHistory uses getVisitsPaginated`() = runTest {
val provider = DefaultPagedHistoryProvider(
historyStorage = storage,
historyImprovementFeatures = false,
@ -145,7 +145,7 @@ class PagedHistoryProviderTest {
}
@Test
fun `history metadata matching lower bound`() = runBlockingTest {
fun `history metadata matching lower bound`() = runTest {
val provider = DefaultPagedHistoryProvider(
historyStorage = storage,
historyImprovementFeatures = false,
@ -215,7 +215,7 @@ class PagedHistoryProviderTest {
}
@Test
fun `history metadata matching upper bound`() = runBlockingTest {
fun `history metadata matching upper bound`() = runTest {
val provider = DefaultPagedHistoryProvider(
historyStorage = storage,
historyImprovementFeatures = false,
@ -285,7 +285,7 @@ class PagedHistoryProviderTest {
}
@Test
fun `redirects are filtered out from history metadata groups`() = runBlockingTest {
fun `redirects are filtered out from history metadata groups`() = runTest {
val provider = DefaultPagedHistoryProvider(
historyStorage = storage,
historyImprovementFeatures = false,

@ -15,7 +15,7 @@ import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkStatic
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
@ -68,7 +68,7 @@ class MetricsUtilsTest {
}
@Test
fun `getHashedIdentifier() returns a hashed identifier`() {
fun `getHashedIdentifier() returns a hashed identifier`() = runTest {
val testId = "test-value-id"
val testPackageName = "org.mozilla-test.fenix"
val mockedHexReturn = "mocked-HEX"
@ -87,9 +87,7 @@ class MetricsUtilsTest {
mockkObject(MetricsUtils)
every { MetricsUtils.getAdvertisingID(context) } returns testId
every { MetricsUtils.getHashingSalt() } returns testPackageName
runBlocking {
assertEquals(mockedHexReturn, MetricsUtils.getHashedIdentifier(context))
}
assertEquals(mockedHexReturn, MetricsUtils.getHashedIdentifier(context))
// Check that the digest of the identifier matches with what we expect.
// Please note that in the real world, Base64.encodeToString would encode

@ -23,7 +23,7 @@ import io.mockk.unmockkStatic
import io.mockk.verify
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.appservices.places.BookmarkRoot
import mozilla.components.browser.state.action.CustomTabListAction
import mozilla.components.browser.state.state.BrowserState
@ -48,6 +48,7 @@ import mozilla.components.support.base.feature.ViewBoundFeatureWrapper
import mozilla.components.support.test.ext.joinBlocking
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@ -149,7 +150,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun handleToolbarBookmarkPressWithReaderModeInactive() = runBlockingTest {
fun handleToolbarBookmarkPressWithReaderModeInactive() = runTest {
val item = ToolbarMenu.Item.Bookmark
val expectedTitle = "Mozilla"
@ -184,7 +185,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `IF reader mode is active WHEN bookmark menu item is pressed THEN menu item is handled`() = runBlockingTest {
fun `IF reader mode is active WHEN bookmark menu item is pressed THEN menu item is handled`() = runTest {
val item = ToolbarMenu.Item.Bookmark
val expectedTitle = "Mozilla"
val readerUrl = "moz-extension://1234"
@ -218,7 +219,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN open in Fenix menu item is pressed THEN menu item is handled correctly`() = runBlockingTest {
fun `WHEN open in Fenix menu item is pressed THEN menu item is handled correctly`() = runTest {
val customTab = createCustomTab("https://mozilla.org")
browserStore.dispatch(CustomTabListAction.AddCustomTabAction(customTab)).joinBlocking()
val controller = createController(
@ -239,7 +240,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN reader mode menu item is pressed THEN handle appearance change`() = runBlockingTest {
fun `WHEN reader mode menu item is pressed THEN handle appearance change`() = runTest {
val item = ToolbarMenu.Item.CustomizeReaderView
assertFalse(ReaderMode.appearance.testHasValue())
@ -253,7 +254,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN quit menu item is pressed THEN menu item is handled correctly`() = runBlockingTest {
fun `WHEN quit menu item is pressed THEN menu item is handled correctly`() = runTest {
val item = ToolbarMenu.Item.Quit
val testScope = this
@ -265,7 +266,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN backwards nav menu item is pressed THEN the session navigates back with active session`() = runBlockingTest {
fun `WHEN backwards nav menu item is pressed THEN the session navigates back with active session`() = runTest {
val item = ToolbarMenu.Item.Back(false)
val controller = createController(scope = this, store = browserStore)
@ -282,7 +283,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN backwards nav menu item is long pressed THEN the session navigates back with no active session`() = runBlockingTest {
fun `WHEN backwards nav menu item is long pressed THEN the session navigates back with no active session`() = runTest {
val item = ToolbarMenu.Item.Back(true)
val controller = createController(scope = this, store = browserStore)
@ -300,7 +301,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN forward nav menu item is pressed THEN the session navigates forward to active session`() = runBlockingTest {
fun `WHEN forward nav menu item is pressed THEN the session navigates forward to active session`() = runTest {
val item = ToolbarMenu.Item.Forward(false)
val controller = createController(scope = this, store = browserStore)
@ -317,7 +318,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN forward nav menu item is long pressed THEN the browser navigates forward with no active session`() = runBlockingTest {
fun `WHEN forward nav menu item is long pressed THEN the browser navigates forward with no active session`() = runTest {
val item = ToolbarMenu.Item.Forward(true)
val controller = createController(scope = this, store = browserStore)
@ -336,7 +337,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN reload nav menu item is pressed THEN the session reloads from cache`() = runBlockingTest {
fun `WHEN reload nav menu item is pressed THEN the session reloads from cache`() = runTest {
val item = ToolbarMenu.Item.Reload(false)
val controller = createController(scope = this, store = browserStore)
@ -353,7 +354,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN reload nav menu item is long pressed THEN the session reloads with no cache`() = runBlockingTest {
fun `WHEN reload nav menu item is long pressed THEN the session reloads with no cache`() = runTest {
val item = ToolbarMenu.Item.Reload(true)
val controller = createController(scope = this, store = browserStore)
@ -375,7 +376,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN stop nav menu item is pressed THEN the session stops loading`() = runBlockingTest {
fun `WHEN stop nav menu item is pressed THEN the session stops loading`() = runTest {
val item = ToolbarMenu.Item.Stop
val controller = createController(scope = this, store = browserStore)
@ -392,7 +393,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN settings menu item is pressed THEN menu item is handled`() = runBlockingTest {
fun `WHEN settings menu item is pressed THEN menu item is handled`() = runTest {
val item = ToolbarMenu.Item.Settings
val controller = createController(scope = this, store = browserStore)
@ -410,7 +411,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN bookmark menu item is pressed THEN navigate to bookmarks page`() = runBlockingTest {
fun `WHEN bookmark menu item is pressed THEN navigate to bookmarks page`() = runTest {
val item = ToolbarMenu.Item.Bookmarks
val controller = createController(scope = this, store = browserStore)
@ -428,7 +429,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN history menu item is pressed THEN navigate to history page`() = runBlockingTest {
fun `WHEN history menu item is pressed THEN navigate to history page`() = runTest {
val item = ToolbarMenu.Item.History
val controller = createController(scope = this, store = browserStore)
@ -446,7 +447,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN request desktop menu item is toggled On THEN desktop site is requested for the session`() = runBlockingTest {
fun `WHEN request desktop menu item is toggled On THEN desktop site is requested for the session`() = runTest {
val requestDesktopSiteUseCase: SessionUseCases.RequestDesktopSiteUseCase =
mockk(relaxed = true)
val item = ToolbarMenu.Item.RequestDesktop(true)
@ -472,7 +473,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN request desktop menu item is toggled Off THEN mobile site is requested for the session`() = runBlockingTest {
fun `WHEN request desktop menu item is toggled Off THEN mobile site is requested for the session`() = runTest {
val requestDesktopSiteUseCase: SessionUseCases.RequestDesktopSiteUseCase =
mockk(relaxed = true)
val item = ToolbarMenu.Item.RequestDesktop(false)
@ -498,7 +499,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN add to shortcuts menu item is pressed THEN add site AND show snackbar`() = runBlockingTest {
fun `WHEN add to shortcuts menu item is pressed THEN add site AND show snackbar`() = runTestOnMain {
val item = ToolbarMenu.Item.AddToTopSites
val addPinnedSiteUseCase: TopSitesUseCases.AddPinnedSiteUseCase = mockk(relaxed = true)
@ -522,7 +523,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `GIVEN a shortcut page is open WHEN remove from shortcuts is pressed THEN show snackbar`() = runBlockingTest {
fun `GIVEN a shortcut page is open WHEN remove from shortcuts is pressed THEN show snackbar`() = runTestOnMain {
val snackbarMessage = "Site removed"
val item = ToolbarMenu.Item.RemoveFromTopSites
val removePinnedSiteUseCase: TopSitesUseCases.RemoveTopSiteUseCase =
@ -550,7 +551,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN addon extensions menu item is pressed THEN navigate to addons manager`() = runBlockingTest {
fun `WHEN addon extensions menu item is pressed THEN navigate to addons manager`() = runTest {
val item = ToolbarMenu.Item.AddonsManager
val controller = createController(scope = this, store = browserStore)
@ -565,7 +566,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN Add To Home Screen menu item is pressed THEN add site`() = runBlockingTest {
fun `WHEN Add To Home Screen menu item is pressed THEN add site`() = runTest {
val item = ToolbarMenu.Item.AddToHomeScreen
val controller = createController(scope = this, store = browserStore)
@ -580,7 +581,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `IF reader mode is inactive WHEN share menu item is pressed THEN navigate to share screen`() = runBlockingTest {
fun `IF reader mode is inactive WHEN share menu item is pressed THEN navigate to share screen`() = runTest {
val item = ToolbarMenu.Item.Share
val title = "Mozilla"
val url = "https://mozilla.org"
@ -613,7 +614,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `IF reader mode is active WHEN share menu item is pressed THEN navigate to share screen`() = runBlockingTest {
fun `IF reader mode is active WHEN share menu item is pressed THEN navigate to share screen`() = runTest {
val item = ToolbarMenu.Item.Share
val title = "Mozilla"
val readerUrl = "moz-extension://1234"
@ -646,7 +647,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN Find In Page menu item is pressed THEN launch finder`() = runBlockingTest {
fun `WHEN Find In Page menu item is pressed THEN launch finder`() = runTest {
val item = ToolbarMenu.Item.FindInPage
var launcherInvoked = false
@ -662,7 +663,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `IF one or more collection exists WHEN Save To Collection menu item is pressed THEN navigate to save collection page`() = runBlockingTest {
fun `IF one or more collection exists WHEN Save To Collection menu item is pressed THEN navigate to save collection page`() = runTest {
val item = ToolbarMenu.Item.SaveToCollection
val cachedTabCollections: List<TabCollection> = mockk(relaxed = true)
every { tabCollectionStorage.cachedTabCollections } returns cachedTabCollections
@ -697,7 +698,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `IF no collection exists WHEN Save To Collection menu item is pressed THEN navigate to create collection page`() = runBlockingTest {
fun `IF no collection exists WHEN Save To Collection menu item is pressed THEN navigate to create collection page`() = runTest {
val item = ToolbarMenu.Item.SaveToCollection
val cachedTabCollectionsEmpty: List<TabCollection> = emptyList()
every { tabCollectionStorage.cachedTabCollections } returns cachedTabCollectionsEmpty
@ -731,7 +732,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `WHEN New Tab menu item is pressed THEN navigate to a new tab home`() = runBlockingTest {
fun `WHEN New Tab menu item is pressed THEN navigate to a new tab home`() = runTest {
val item = ToolbarMenu.Item.NewTab
val controller = createController(scope = this, store = browserStore)
@ -750,7 +751,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `GIVEN account exists and the user is signed in WHEN sign in to sync menu item is pressed THEN navigate to account settings`() = runBlockingTest {
fun `GIVEN account exists and the user is signed in WHEN sign in to sync menu item is pressed THEN navigate to account settings`() = runTest {
val item = ToolbarMenu.Item.SyncAccount(AccountState.AUTHENTICATED)
val accountSettingsDirections = BrowserFragmentDirections.actionGlobalAccountSettingsFragment()
val controller = createController(scope = this, store = browserStore)
@ -761,7 +762,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `GIVEN account exists and the user is not signed in WHEN sign in to sync menu item is pressed THEN navigate to account problem fragment`() = runBlockingTest {
fun `GIVEN account exists and the user is not signed in WHEN sign in to sync menu item is pressed THEN navigate to account problem fragment`() = runTest {
val item = ToolbarMenu.Item.SyncAccount(AccountState.NEEDS_REAUTHENTICATION)
val accountProblemDirections = BrowserFragmentDirections.actionGlobalAccountProblemFragment()
val controller = createController(scope = this, store = browserStore)
@ -772,7 +773,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `GIVEN account doesn't exist WHEN sign in to sync menu item is pressed THEN navigate to sign in`() = runBlockingTest {
fun `GIVEN account doesn't exist WHEN sign in to sync menu item is pressed THEN navigate to sign in`() = runTest {
val item = ToolbarMenu.Item.SyncAccount(AccountState.NO_ACCOUNT)
val turnOnSyncDirections = BrowserFragmentDirections.actionGlobalTurnOnSync()
val controller = createController(scope = this, store = browserStore)
@ -783,7 +784,7 @@ class DefaultBrowserToolbarMenuControllerTest {
}
@Test
fun `GIVEN the default browser experiment WHEN SetDefaultBrowser menu item is pressed THEN proper metrics are recorded`() = runBlockingTest {
fun `GIVEN the default browser experiment WHEN SetDefaultBrowser menu item is pressed THEN proper metrics are recorded`() = runTest {
val item = ToolbarMenu.Item.SetDefaultBrowser
val store: BrowserStore = mockk()

@ -6,11 +6,11 @@ package org.mozilla.fenix.exceptions.login
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import mozilla.components.feature.logins.exceptions.LoginException
import mozilla.components.feature.logins.exceptions.LoginExceptionStorage
import org.junit.After
import org.junit.Before
import org.junit.Test
@ -18,7 +18,7 @@ class LoginExceptionsInteractorTest {
private lateinit var loginExceptionStorage: LoginExceptionStorage
private lateinit var interactor: LoginExceptionsInteractor
private val scope = TestCoroutineScope()
private val scope = TestScope(UnconfinedTestDispatcher())
@Before
fun setup() {
@ -26,19 +26,14 @@ class LoginExceptionsInteractorTest {
interactor = DefaultLoginExceptionsInteractor(scope, loginExceptionStorage)
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun onDeleteAll() = scope.runBlockingTest {
fun onDeleteAll() = scope.runTest {
interactor.onDeleteAll()
verify { loginExceptionStorage.deleteAllLoginExceptions() }
}
@Test
fun onDeleteOne() = scope.runBlockingTest {
fun onDeleteOne() = scope.runTest {
val exceptionsItem: LoginException = mockk()
interactor.onDeleteOne(exceptionsItem)
verify { loginExceptionStorage.removeLoginException(exceptionsItem) }

@ -4,7 +4,7 @@
package org.mozilla.fenix.exceptions.trackingprotection
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.engine.content.blocking.TrackingProtectionException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
@ -12,7 +12,7 @@ import org.junit.Test
class TrackingProtectionExceptionsFragmentStoreTest {
@Test
fun onChange() = runBlocking {
fun onChange() = runTest {
val initialState = ExceptionsFragmentState()
val store = ExceptionsFragmentStore(initialState)
val newExceptionsItem = ExceptionItem("URL")

@ -9,7 +9,7 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.support.test.robolectric.testContext
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@ -62,7 +62,7 @@ class NimbusMessagingStorageTest {
}
@Test
fun `WHEN calling getMessages THEN provide a list of available messages`() = runBlockingTest {
fun `WHEN calling getMessages THEN provide a list of available messages`() = runTest {
val message = storage.getMessages().first()
assertEquals("message-1", message.id)
@ -71,7 +71,7 @@ class NimbusMessagingStorageTest {
@Test
fun `WHEN calling getMessages THEN provide a list of sorted messages by priority`() =
runBlockingTest {
runTest {
val messages = mapOf(
"low-message" to createMessageData(style = "low-priority"),
"high-message" to createMessageData(style = "high-priority"),
@ -111,7 +111,7 @@ class NimbusMessagingStorageTest {
@Test
fun `GIVEN pressed message WHEN calling getMessages THEN filter out the pressed message`() =
runBlockingTest {
runTest {
val metadataList = mapOf(
"pressed-message" to Message.Metadata(id = "pressed-message", pressed = true),
"normal-message" to Message.Metadata(id = "normal-message", pressed = false)
@ -147,7 +147,7 @@ class NimbusMessagingStorageTest {
@Test
fun `GIVEN dismissed message WHEN calling getMessages THEN filter out the dismissed message`() =
runBlockingTest {
runTest {
val metadataList = mapOf(
"dismissed-message" to Message.Metadata(id = "dismissed-message", dismissed = true),
"normal-message" to Message.Metadata(id = "normal-message", dismissed = false)
@ -183,7 +183,7 @@ class NimbusMessagingStorageTest {
@Test
fun `GIVEN a message that the maxDisplayCount WHEN calling getMessages THEN filter out the message`() =
runBlockingTest {
runTest {
val metadataList = mapOf(
"shown-many-times-message" to Message.Metadata(
id = "shown-many-times-message",
@ -223,7 +223,7 @@ class NimbusMessagingStorageTest {
}
@Test
fun `GIVEN a malformed message WHEN calling getMessages THEN provide a list of messages ignoring the malformed one`() = runBlockingTest {
fun `GIVEN a malformed message WHEN calling getMessages THEN provide a list of messages ignoring the malformed one`() = runTest {
val messages = storage.getMessages()
val firstMessage = messages.first()
@ -271,7 +271,7 @@ class NimbusMessagingStorageTest {
}
@Test
fun `WHEN calling updateMetadata THEN delegate to metadataStorage`() = runBlockingTest {
fun `WHEN calling updateMetadata THEN delegate to metadataStorage`() = runTest {
storage.updateMetadata(mockk(relaxed = true))

@ -10,7 +10,7 @@ import io.mockk.coVerify
import io.mockk.just
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.support.test.robolectric.testContext
import org.json.JSONArray
import org.json.JSONObject
@ -43,7 +43,7 @@ class OnDiskMessageMetadataStorageTest {
@Test
fun `GIVEN metadata is not loaded from disk WHEN calling getMetadata THEN load it`() =
runBlockingTest {
runTest {
val spiedStorage = spyk(storage)
coEvery { spiedStorage.readFromDisk() } returns emptyMap()
@ -55,7 +55,7 @@ class OnDiskMessageMetadataStorageTest {
@Test
fun `GIVEN metadata is loaded from disk WHEN calling getMetadata THEN do not load it from disk`() =
runBlockingTest {
runTest {
val spiedStorage = spyk(storage)
spiedStorage.metadataMap = hashMapOf("" to Message.Metadata("id"))
@ -66,7 +66,7 @@ class OnDiskMessageMetadataStorageTest {
}
@Test
fun `WHEN calling addMetadata THEN add in memory and disk`() = runBlockingTest {
fun `WHEN calling addMetadata THEN add in memory and disk`() = runTest {
val spiedStorage = spyk(storage)
assertTrue(spiedStorage.metadataMap.isEmpty())
@ -80,7 +80,7 @@ class OnDiskMessageMetadataStorageTest {
}
@Test
fun `WHEN calling updateMetadata THEN delegate to addMetadata`() = runBlockingTest {
fun `WHEN calling updateMetadata THEN delegate to addMetadata`() = runTest {
val spiedStorage = spyk(storage)
val metadata = Message.Metadata("id")
coEvery { spiedStorage.writeToDisk() } just Runs

@ -12,10 +12,11 @@ import io.mockk.just
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.components.lib.state.MiddlewareContext
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
@ -41,8 +42,9 @@ import org.mozilla.fenix.nimbus.StyleData
@RunWith(FenixRobolectricTestRunner::class)
class MessagingMiddlewareTest {
private val coroutineScope = TestCoroutineScope()
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val coroutineScope = coroutinesTestRule.scope
private lateinit var store: AppStore
private lateinit var middleware: MessagingMiddleware
private lateinit var messagingStorage: NimbusMessagingStorage
@ -65,7 +67,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN Restore THEN get messages from the storage and UpdateMessages`() {
fun `WHEN Restore THEN get messages from the storage and UpdateMessages`() = runTestOnMain {
val messages: List<Message> = emptyList()
coEvery { messagingStorage.getMessages() } returns messages
@ -76,7 +78,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN Restore THEN getNextMessage from the storage and UpdateMessageToShow`() {
fun `WHEN Restore THEN getNextMessage from the storage and UpdateMessageToShow`() = runTestOnMain {
val message: Message = mockk(relaxed = true)
val appState: AppState = mockk(relaxed = true)
val messagingState: MessagingState = mockk(relaxed = true)
@ -92,7 +94,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN MessageClicked THEN update storage`() {
fun `WHEN MessageClicked THEN update storage`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -115,7 +117,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN MessageDismissed THEN update storage`() {
fun `WHEN MessageDismissed THEN update storage`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -141,7 +143,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN MessageDisplayed THEN update storage`() {
fun `WHEN MessageDisplayed THEN update storage`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -169,7 +171,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN onMessageDismissed THEN updateMetadata,removeMessage , UpdateMessages and removeMessageToShowIfNeeded`() {
fun `WHEN onMessageDismissed THEN updateMetadata,removeMessage , UpdateMessages and removeMessageToShowIfNeeded`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -192,7 +194,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN removeMessage THEN remove the message`() {
fun `WHEN removeMessage THEN remove the message`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -215,7 +217,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN consumeMessageToShowIfNeeded THEN consume the message`() {
fun `WHEN consumeMessageToShowIfNeeded THEN consume the message`() = runTestOnMain {
val message = Message(
"control-id",
mockk(relaxed = true),
@ -237,7 +239,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `WHEN updateMessage THEN update available messages`() {
fun `WHEN updateMessage THEN update available messages`() = runTestOnMain {
val oldMessage = Message(
"oldMessage",
mockk(relaxed = true),
@ -276,7 +278,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `GIVEN a message with that not surpassed the maxDisplayCount WHEN onMessagedDisplayed THEN update the available messages and the updateMetadata`() {
fun `GIVEN a message with that not surpassed the maxDisplayCount WHEN onMessagedDisplayed THEN update the available messages and the updateMetadata`() = runTestOnMain {
val style: StyleData = mockk(relaxed = true)
val oldMessageData: MessageData = mockk(relaxed = true)
val oldMessage = Message(
@ -308,7 +310,7 @@ class MessagingMiddlewareTest {
}
@Test
fun `GIVEN a message with that surpassed the maxDisplayCount WHEN onMessagedDisplayed THEN remove the message and consume it`() {
fun `GIVEN a message with that surpassed the maxDisplayCount WHEN onMessagedDisplayed THEN remove the message and consume it`() = runTestOnMain {
val style: StyleData = mockk(relaxed = true)
val oldMessageData: MessageData = mockk(relaxed = true)
val oldMessage = Message(

@ -15,7 +15,6 @@ import io.mockk.spyk
import io.mockk.unmockkStatic
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.components.browser.state.action.SearchAction
import mozilla.components.browser.state.action.TabListAction
import mozilla.components.browser.state.search.RegionState
@ -37,7 +36,6 @@ import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.ext.joinBlocking
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@ -96,7 +94,7 @@ class DefaultSessionControlControllerTest {
private val selectTabUseCase: TabsUseCases = mockk(relaxed = true)
private val settings: Settings = mockk(relaxed = true)
private val analytics: Analytics = mockk(relaxed = true)
private val scope = TestCoroutineScope()
private val scope = coroutinesTestRule.scope
private val searchEngine = SearchEngine(
id = "test",
name = "Test Engine",
@ -154,11 +152,6 @@ class DefaultSessionControlControllerTest {
every { activity.components.analytics } returns analytics
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun handleCollectionAddTabTapped() {
val collection = mockk<TabCollection> {

@ -13,10 +13,12 @@ import io.mockk.verify
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.components.service.pocket.PocketRecommendedStory
import mozilla.components.service.pocket.PocketStoriesService
import mozilla.components.support.test.ext.joinBlocking
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Rule
import org.junit.Test
import org.mozilla.fenix.components.AppStore
import org.mozilla.fenix.components.appstate.AppAction
@ -27,14 +29,16 @@ import org.mozilla.fenix.home.pocket.PocketRecommendedStoriesCategory
import org.mozilla.fenix.home.pocket.PocketRecommendedStoriesSelectedCategory
class PocketUpdatesMiddlewareTest {
@get:Rule
val mainCoroutineTestRule = MainCoroutineRule()
@Test
fun `WHEN PocketStoriesShown is dispatched THEN update PocketStoriesService`() {
fun `WHEN PocketStoriesShown is dispatched THEN update PocketStoriesService`() = runTestOnMain {
val story1 = PocketRecommendedStory("title", "url1", "imageUrl", "publisher", "category", 0, timesShown = 0)
val story2 = story1.copy("title2", "url2")
val story3 = story1.copy("title3", "url3")
val coroutineScope = TestCoroutineScope()
val pocketService: PocketStoriesService = mockk(relaxed = true)
val pocketMiddleware = PocketUpdatesMiddleware(pocketService, mockk(), coroutineScope)
val pocketMiddleware = PocketUpdatesMiddleware(pocketService, mockk(), this)
val appstore = AppStore(
AppState(
pocketStories = listOf(story1, story2, story3)
@ -48,12 +52,12 @@ class PocketUpdatesMiddlewareTest {
}
@Test
fun `WHEN persistStories is called THEN update PocketStoriesService`() {
fun `WHEN persistStories is called THEN update PocketStoriesService`() = runTestOnMain {
val stories: List<PocketRecommendedStory> = mockk()
val pocketService: PocketStoriesService = mockk(relaxed = true)
persistStories(
coroutineScope = TestCoroutineScope(),
coroutineScope = this,
pocketStoriesService = pocketService,
updatedStories = stories
)
@ -63,7 +67,7 @@ class PocketUpdatesMiddlewareTest {
@Test
@Suppress("UNCHECKED_CAST")
fun `WHEN PocketStoriesCategoriesChange is dispatched THEN intercept and dispatch PocketStoriesCategoriesSelectionsChange`() {
fun `WHEN PocketStoriesCategoriesChange is dispatched THEN intercept and dispatch PocketStoriesCategoriesSelectionsChange`() = runTestOnMain {
val persistedSelectedCategory: SelectedPocketStoriesCategory = mockk {
every { name } returns "testCategory"
every { selectionTimestamp } returns 123
@ -76,7 +80,7 @@ class PocketUpdatesMiddlewareTest {
every { data } returns flowOf(persistedSelectedCategories)
} as DataStore<SelectedPocketStoriesCategories>
val currentCategories = listOf(mockk<PocketRecommendedStoriesCategory>())
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, TestCoroutineScope())
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, this)
val appStore = spyk(
AppStore(
AppState(
@ -102,13 +106,13 @@ class PocketUpdatesMiddlewareTest {
@Test
@Suppress("UNCHECKED_CAST")
fun `WHEN SelectPocketStoriesCategory is dispatched THEN persist details in DataStore`() {
fun `WHEN SelectPocketStoriesCategory is dispatched THEN persist details in DataStore`() = runTestOnMain {
val categ1 = PocketRecommendedStoriesCategory("categ1")
val categ2 = PocketRecommendedStoriesCategory("categ2")
val dataStore: DataStore<SelectedPocketStoriesCategories> =
mockk<FakeDataStore<SelectedPocketStoriesCategories>>(relaxed = true) as
DataStore<SelectedPocketStoriesCategories>
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, TestCoroutineScope())
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, this)
val appStore = spyk(
AppStore(
AppState(
@ -126,13 +130,13 @@ class PocketUpdatesMiddlewareTest {
@Test
@Suppress("UNCHECKED_CAST")
fun `WHEN DeselectPocketStoriesCategory is dispatched THEN persist details in DataStore`() {
fun `WHEN DeselectPocketStoriesCategory is dispatched THEN persist details in DataStore`() = runTestOnMain {
val categ1 = PocketRecommendedStoriesCategory("categ1")
val categ2 = PocketRecommendedStoriesCategory("categ2")
val dataStore: DataStore<SelectedPocketStoriesCategories> =
mockk<FakeDataStore<SelectedPocketStoriesCategories>>(relaxed = true) as
DataStore<SelectedPocketStoriesCategories>
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, TestCoroutineScope())
val pocketMiddleware = PocketUpdatesMiddleware(mockk(), dataStore, this)
val appStore = spyk(
AppStore(
AppState(
@ -150,12 +154,12 @@ class PocketUpdatesMiddlewareTest {
@Test
@Suppress("UNCHECKED_CAST")
fun `WHEN persistCategories is called THEN update dataStore`() {
fun `WHEN persistCategories is called THEN update dataStore`() = runTestOnMain {
val dataStore: DataStore<SelectedPocketStoriesCategories> =
mockk<FakeDataStore<SelectedPocketStoriesCategories>>(relaxed = true) as
DataStore<SelectedPocketStoriesCategories>
persistSelectedCategories(TestCoroutineScope(), listOf(mockk(relaxed = true)), dataStore)
persistSelectedCategories(this, listOf(mockk(relaxed = true)), dataStore)
// Seems like the most we can test is that an update was made.
coVerify { dataStore.updateData(any()) }
@ -163,7 +167,7 @@ class PocketUpdatesMiddlewareTest {
@Test
@Suppress("UNCHECKED_CAST")
fun `WHEN restoreSelectedCategories is called THEN dispatch PocketStoriesCategoriesSelectionsChange with data read from the persistence layer`() {
fun `WHEN restoreSelectedCategories is called THEN dispatch PocketStoriesCategoriesSelectionsChange with data read from the persistence layer`() = runTestOnMain {
val persistedSelectedCategory: SelectedPocketStoriesCategory = mockk {
every { name } returns "testCategory"
every { selectionTimestamp } returns 123
@ -181,7 +185,7 @@ class PocketUpdatesMiddlewareTest {
)
restoreSelectedCategories(
coroutineScope = TestCoroutineScope(),
coroutineScope = this,
currentCategories = currentCategories,
store = appStore,
selectedPocketCategoriesDataStore = dataStore

@ -10,7 +10,7 @@ import io.mockk.Called
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.state.SessionState
import mozilla.components.concept.engine.EngineSession
import mozilla.components.feature.intent.ext.getSessionId
@ -28,7 +28,7 @@ class FennecBookmarkShortcutsIntentProcessorTest {
private val addNewTabUseCase = mockk<TabsUseCases.AddNewTabUseCase>(relaxed = true)
@Test
fun `do not process blank Intents`() = runBlocking {
fun `do not process blank Intents`() = runTest {
val processor = FennecBookmarkShortcutsIntentProcessor(addNewTabUseCase)
val fennecShortcutsIntent = Intent(ACTION_FENNEC_HOMESCREEN_SHORTCUT)
fennecShortcutsIntent.data = Uri.parse("http://mozilla.org")
@ -42,7 +42,7 @@ class FennecBookmarkShortcutsIntentProcessorTest {
}
@Test
fun `processing a Fennec shortcut Intent results in loading it's URL in a new Session`() = runBlocking {
fun `processing a Fennec shortcut Intent results in loading it's URL in a new Session`() = runTest {
val expectedSessionId = "test"
val processor = FennecBookmarkShortcutsIntentProcessor(addNewTabUseCase)
val fennecShortcutsIntent = Intent(ACTION_FENNEC_HOMESCREEN_SHORTCUT)

@ -12,12 +12,12 @@ import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import mozilla.appservices.places.BookmarkRoot
import mozilla.components.concept.engine.EngineSession
import mozilla.components.concept.engine.EngineSession.LoadUrlFlags.Companion.ALLOW_JAVASCRIPT_URL
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import mozilla.telemetry.glean.testing.GleanTestRule
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@ -95,7 +95,7 @@ class DefaultRecentBookmarksControllerTest {
}
@Test
fun `WHEN show all recently saved bookmark is clicked THEN the bookmarks root is opened`() = runBlockingTest {
fun `WHEN show all recently saved bookmark is clicked THEN the bookmarks root is opened`() = runTestOnMain {
every { navController.currentDestination } returns mockk {
every { id } returns R.id.homeFragment
}

@ -7,13 +7,13 @@ package org.mozilla.fenix.home.recentbookmarks
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.concept.storage.BookmarkNode
import mozilla.components.support.test.libstate.ext.waitUntilIdle
import mozilla.components.support.test.middleware.CaptureActionsMiddleware
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
@ -38,6 +38,7 @@ class RecentBookmarksFeatureTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val scope = coroutinesTestRule.scope
@Before
fun setup() {
@ -46,11 +47,11 @@ class RecentBookmarksFeatureTest {
@Test
fun `GIVEN no recent bookmarks WHEN feature starts THEN fetch bookmarks and notify store`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val feature = RecentBookmarksFeature(
appStore,
bookmarksUseCases,
CoroutineScope(testDispatcher),
scope,
testDispatcher
)
@ -58,7 +59,7 @@ class RecentBookmarksFeatureTest {
feature.start()
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
appStore.waitUntilIdle()
coVerify {

@ -7,13 +7,14 @@ package org.mozilla.fenix.home.recentvisits
import io.mockk.coVerify
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.state.state.createTab
import mozilla.components.concept.storage.DocumentType
import mozilla.components.concept.storage.HistoryMetadataKey
import mozilla.components.concept.storage.HistoryMetadataObservation
import mozilla.components.concept.storage.HistoryMetadataStorage
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
@ -28,20 +29,20 @@ class HistoryMetadataServiceTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
val testDispatcher = coroutinesTestRule.testDispatcher
private val scope = coroutinesTestRule.scope
@Before
fun setup() {
storage = mockk(relaxed = true)
service = DefaultHistoryMetadataService(storage, CoroutineScope(testDispatcher))
service = DefaultHistoryMetadataService(storage, scope)
}
@Test
fun `GIVEN a regular page WHEN metadata is created THEN a regular document type observation is recorded`() {
fun `GIVEN a regular page WHEN metadata is created THEN a regular document type observation is recorded`() = runTestOnMain {
val parent = createTab("https://mozilla.org")
val tab = createTab("https://blog.mozilla.org", parent = parent)
service.createMetadata(tab, searchTerms = "hello", referrerUrl = parent.content.url)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val expectedKey = HistoryMetadataKey(url = tab.content.url, searchTerm = "hello", referrerUrl = parent.content.url)
val expectedObservation = HistoryMetadataObservation.DocumentTypeObservation(documentType = DocumentType.Regular)
@ -49,10 +50,10 @@ class HistoryMetadataServiceTest {
}
@Test
fun `GIVEN a media page WHEN metadata is created THEN a media document type observation is recorded`() {
fun `GIVEN a media page WHEN metadata is created THEN a media document type observation is recorded`() = runTestOnMain {
val tab = createTab("https://media.mozilla.org", mediaSessionState = mockk())
service.createMetadata(tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val expectedKey = HistoryMetadataKey(url = tab.content.url)
val expectedObservation = HistoryMetadataObservation.DocumentTypeObservation(documentType = DocumentType.Media)
@ -60,11 +61,11 @@ class HistoryMetadataServiceTest {
}
@Test
fun `GIVEN existing metadata WHEN metadata is created THEN correct document type observation is recorded`() {
fun `GIVEN existing metadata WHEN metadata is created THEN correct document type observation is recorded`() = runTestOnMain {
val existingKey = HistoryMetadataKey(url = "https://media.mozilla.org", referrerUrl = "https://mozilla.org")
val tab = createTab("https://media.mozilla.org", historyMetadata = existingKey)
service.createMetadata(tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
var expectedKey = HistoryMetadataKey(url = tab.content.url, referrerUrl = existingKey.referrerUrl)
var expectedObservation = HistoryMetadataObservation.DocumentTypeObservation(documentType = DocumentType.Regular)
@ -72,7 +73,7 @@ class HistoryMetadataServiceTest {
val otherTab = createTab("https://blog.mozilla.org", historyMetadata = existingKey)
service.createMetadata(otherTab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
expectedKey = HistoryMetadataKey(url = otherTab.content.url)
expectedObservation = HistoryMetadataObservation.DocumentTypeObservation(documentType = DocumentType.Regular)
@ -80,12 +81,12 @@ class HistoryMetadataServiceTest {
}
@Test
fun `WHEN metadata is updated THEN a view time observation is recorded`() {
fun `WHEN metadata is updated THEN a view time observation is recorded`() = runTestOnMain {
val now = System.currentTimeMillis()
val key = HistoryMetadataKey(url = "https://blog.mozilla.org")
val tab = createTab(key.url, historyMetadata = key, lastAccess = now - 60 * 1000)
service.updateMetadata(key, tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val observation = slot<HistoryMetadataObservation.ViewTimeObservation>()
coVerify { storage.noteHistoryMetadataObservation(key, capture(observation)) }
@ -93,22 +94,22 @@ class HistoryMetadataServiceTest {
}
@Test
fun `WHEN metadata is updated for a tab with no lastAccess THEN view time observation is not recorded`() {
fun `WHEN metadata is updated for a tab with no lastAccess THEN view time observation is not recorded`() = runTestOnMain {
val key = HistoryMetadataKey(url = "https://blog.mozilla.org")
val tab = createTab(key.url, historyMetadata = key, lastAccess = 0)
service.updateMetadata(key, tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
coVerify(exactly = 0) { storage.noteHistoryMetadataObservation(key, any()) }
}
@Test
fun `WHEN metadata is updated for a tab with unchanged lastAccess THEN view time observation is not recorded`() {
fun `WHEN metadata is updated for a tab with unchanged lastAccess THEN view time observation is not recorded`() = runTestOnMain {
val now = System.currentTimeMillis()
val key = HistoryMetadataKey(url = "https://blog.mozilla.org")
val tab = createTab(key.url, historyMetadata = key, lastAccess = now - 60 * 1000)
service.updateMetadata(key, tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val observation = slot<HistoryMetadataObservation.ViewTimeObservation>()
coVerify(exactly = 1) { storage.noteHistoryMetadataObservation(key, capture(observation)) }
@ -116,15 +117,15 @@ class HistoryMetadataServiceTest {
// Now, call update again with the same lastAccess value. Storage method won't be hit again.
service.updateMetadata(key, tab)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
coVerify(exactly = 1) { storage.noteHistoryMetadataObservation(key, any()) }
}
@Test
fun `WHEN cleanup is called THEN old metadata is deleted`() {
fun `WHEN cleanup is called THEN old metadata is deleted`() = runTestOnMain {
val timestamp = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000
service.cleanup(timestamp)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
coVerify { storage.deleteHistoryMetadataOlderThan(timestamp) }
}

@ -10,9 +10,8 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.spyk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.storage.sync.PlacesHistoryStorage
import mozilla.components.concept.storage.DocumentType
import mozilla.components.concept.storage.HistoryHighlight
@ -23,6 +22,7 @@ import mozilla.components.concept.storage.HistoryMetadataStorage
import mozilla.components.support.test.libstate.ext.waitUntilIdle
import mozilla.components.support.test.middleware.CaptureActionsMiddleware
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
@ -49,6 +49,7 @@ class RecentVisitsFeatureTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val scope = coroutinesTestRule.scope
@Before
fun setup() {
@ -58,7 +59,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN no recent visits WHEN feature starts THEN fetch history metadata and highlights then notify store`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val historyEntry = HistoryMetadata(
key = HistoryMetadataKey("http://www.mozilla.com", "mozilla", null),
title = "mozilla",
@ -92,7 +93,7 @@ class RecentVisitsFeatureTest {
@Test
fun `WHEN asking for history highlights THEN use a specific query`() {
testDispatcher.runBlockingTest {
runTestOnMain {
val highlightWeights = slot<HistoryHighlightWeights>()
val highlightsAskedForNumber = slot<Int>()
@ -113,7 +114,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN groups containing history metadata items with the same url WHEN they are added to store THEN entries are deduped`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val historyEntry1 = HistoryMetadata(
key = HistoryMetadataKey("http://www.mozilla.com", "mozilla", null),
title = "mozilla",
@ -171,7 +172,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN different groups containing history metadata items with the same url WHEN they are added to store THEN entries are not deduped`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val now = System.currentTimeMillis()
val historyEntry1 = HistoryMetadata(
key = HistoryMetadataKey("http://www.mozilla.com", "mozilla", null),
@ -228,7 +229,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN history groups WHEN they are added to store THEN they are sorted descending by last updated timestamp`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val now = System.currentTimeMillis()
val historyEntry1 = HistoryMetadata(
key = HistoryMetadataKey("http://www.mozilla.com", "mozilla", null),
@ -285,7 +286,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN multiple groups exist but no highlights WHEN they are added to store THEN only MAX_RESULTS_TOTAL are sent`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val visitsFromSearch = getSearchFromHistoryMetadataItems(10)
val expectedRecentHistoryGroups = visitsFromSearch
// Expect to only have the last accessed 9 groups.
@ -306,7 +307,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN multiple highlights exist but no history groups WHEN they are added to store THEN only MAX_RESULTS_TOTAL are sent`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val highlights = getHistoryHighlightsItems(10)
val expectedRecentHighlights = highlights
// Expect to only have 9 highlights
@ -326,7 +327,7 @@ class RecentVisitsFeatureTest {
@Test
fun `GIVEN multiple history highlights and history groups WHEN they are added to store THEN only last accessed are added`() =
testDispatcher.runBlockingTest {
runTestOnMain {
val visitsFromSearch = getSearchFromHistoryMetadataItems(10)
val directVisits = getDirectVisitsHistoryMetadataItems(10)
val expectedRecentHistoryGroups = visitsFromSearch
@ -644,7 +645,7 @@ class RecentVisitsFeatureTest {
appStore,
historyMetadataStorage,
lazy { historyHightlightsStorage },
CoroutineScope(testDispatcher),
scope,
testDispatcher,
false
)
@ -653,7 +654,7 @@ class RecentVisitsFeatureTest {
feature.start()
testDispatcher.advanceUntilIdle()
scope.advanceUntilIdle()
appStore.waitUntilIdle()
coVerify {

@ -14,7 +14,7 @@ import io.mockk.verify
import io.mockk.verifyOrder
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.state.action.HistoryMetadataAction
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.concept.storage.DocumentType
@ -25,7 +25,7 @@ import mozilla.components.feature.tabs.TabsUseCases.SelectOrAddUseCase
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
@ -49,7 +49,7 @@ class RecentVisitsControllerTest {
val gleanTestRule = GleanTestRule(testContext)
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val scope = coroutinesTestRule.scope
private val selectOrAddTabUseCase: SelectOrAddUseCase = mockk(relaxed = true)
private val navController = mockk<NavController>(relaxed = true)
@ -57,7 +57,6 @@ class RecentVisitsControllerTest {
private lateinit var storage: HistoryMetadataStorage
private lateinit var appStore: AppStore
private lateinit var store: BrowserStore
private val scope = TestCoroutineScope()
private lateinit var controller: DefaultRecentVisitsController
@ -82,13 +81,8 @@ class RecentVisitsControllerTest {
)
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun handleHistoryShowAllClicked() {
fun handleHistoryShowAllClicked() = runTestOnMain {
controller.handleHistoryShowAllClicked()
verify {
@ -100,7 +94,7 @@ class RecentVisitsControllerTest {
}
@Test
fun handleRecentHistoryGroupClicked() {
fun handleRecentHistoryGroupClicked() = runTestOnMain {
val historyEntry = HistoryMetadata(
key = HistoryMetadataKey("http://www.mozilla.com", "mozilla", null),
title = "mozilla",
@ -125,7 +119,7 @@ class RecentVisitsControllerTest {
}
@Test
fun handleRemoveGroup() {
fun handleRemoveGroup() = runTestOnMain {
val historyMetadataKey = HistoryMetadataKey(
"http://www.mozilla.com",
"mozilla",
@ -150,7 +144,7 @@ class RecentVisitsControllerTest {
controller.handleRemoveRecentHistoryGroup(historyGroup.title)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
verify {
store.dispatch(HistoryMetadataAction.DisbandSearchGroupAction(searchTerm = historyGroup.title))
appStore.dispatch(AppAction.DisbandSearchGroupAction(searchTerm = historyGroup.title))
@ -163,7 +157,7 @@ class RecentVisitsControllerTest {
}
@Test
fun handleRecentHistoryHighlightClicked() {
fun handleRecentHistoryHighlightClicked() = runTestOnMain {
val historyHighlight = RecentHistoryHighlight("title", "url")
controller.handleRecentHistoryHighlightClicked(historyHighlight)
@ -175,7 +169,7 @@ class RecentVisitsControllerTest {
}
@Test
fun handleRemoveRecentHistoryHighlight() {
fun handleRemoveRecentHistoryHighlight() = runTestOnMain {
val highlightUrl = "highlightUrl"
controller.handleRemoveRecentHistoryHighlight(highlightUrl)

@ -22,16 +22,17 @@ import io.mockk.slot
import io.mockk.spyk
import io.mockk.verify
import io.mockk.verifyOrder
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.appservices.places.BookmarkRoot
import mozilla.components.concept.engine.EngineSession
import mozilla.components.concept.storage.BookmarkNode
import mozilla.components.concept.storage.BookmarkNodeType
import mozilla.components.feature.tabs.TabsUseCases
import org.junit.After
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mozilla.fenix.BrowserDirection
import org.mozilla.fenix.HomeActivity
@ -44,9 +45,12 @@ import org.mozilla.fenix.ext.components
@Suppress("TooManyFunctions", "LargeClass")
class BookmarkControllerTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val scope = coroutinesTestRule.scope
private val bookmarkStore = spyk(BookmarkFragmentStore(BookmarkFragmentState(null)))
private val context: Context = mockk(relaxed = true)
private val scope = TestCoroutineScope()
private val clipboardManager: ClipboardManager = mockk(relaxUnitFun = true)
private val navController: NavController = mockk(relaxed = true)
private val sharedViewModel: BookmarksSharedViewModel = mockk()
@ -99,11 +103,6 @@ class BookmarkControllerTest {
every { tabsUseCases.addTab } returns addNewTabUseCase
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun `handleBookmarkChanged updates the selected bookmark node`() {
createController().handleBookmarkChanged(tree)
@ -182,7 +181,7 @@ class BookmarkControllerTest {
}
@Test
fun `handleBookmarkExpand should refresh and change the active bookmark node`() {
fun `handleBookmarkExpand should refresh and change the active bookmark node`() = runTestOnMain {
var loadBookmarkNodeInvoked = false
createController(
loadBookmarkNode = {
@ -381,7 +380,7 @@ class BookmarkControllerTest {
}
@Test
fun `handleRequestSync dispatches actions in the correct order`() {
fun `handleRequestSync dispatches actions in the correct order`() = runTestOnMain {
every { homeActivity.components.backgroundServices.accountManager } returns mockk(relaxed = true)
coEvery { homeActivity.bookmarkStorage.getBookmark(any()) } returns tree
@ -394,7 +393,7 @@ class BookmarkControllerTest {
}
@Test
fun `handleBackPressed with one item in backstack should trigger handleBackPressed in NavController`() {
fun `handleBackPressed with one item in backstack should trigger handleBackPressed in NavController`() = runTestOnMain {
every { bookmarkStore.state.guidBackstack } returns listOf(tree.guid)
every { bookmarkStore.state.tree } returns tree

@ -4,7 +4,7 @@
package org.mozilla.fenix.library.bookmarks
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.storage.BookmarkNode
import mozilla.components.concept.storage.BookmarkNodeType
import org.junit.Assert.assertEquals
@ -16,7 +16,7 @@ import org.junit.Test
class BookmarkFragmentStoreTest {
@Test
fun `change the tree of bookmarks starting from an empty tree`() = runBlocking {
fun `change the tree of bookmarks starting from an empty tree`() = runTest {
val initialState = BookmarkFragmentState(null)
val store = BookmarkFragmentStore(initialState)
@ -29,7 +29,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `change the tree of bookmarks starting from an existing tree`() = runBlocking {
fun `change the tree of bookmarks starting from an existing tree`() = runTest {
val initialState = BookmarkFragmentState(tree)
val store = BookmarkFragmentStore(initialState)
@ -42,7 +42,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `changing the tree of bookmarks adds the tree to the visited nodes`() = runBlocking {
fun `changing the tree of bookmarks adds the tree to the visited nodes`() = runTest {
val initialState = BookmarkFragmentState(null)
val store = BookmarkFragmentStore(initialState)
@ -53,7 +53,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `changing to a node that is in the backstack removes backstack items after that node`() = runBlocking {
fun `changing to a node that is in the backstack removes backstack items after that node`() = runTest {
val initialState = BookmarkFragmentState(
null,
guidBackstack = listOf(tree.guid, subfolder.guid, item.guid)
@ -66,7 +66,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `change the tree of bookmarks to the same value`() = runBlocking {
fun `change the tree of bookmarks to the same value`() = runTest {
val initialState = BookmarkFragmentState(tree)
val store = BookmarkFragmentStore(initialState)
@ -79,7 +79,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `ensure selected items remain selected after a tree change`() = runBlocking {
fun `ensure selected items remain selected after a tree change`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Selecting(setOf(item, subfolder)))
val store = BookmarkFragmentStore(initialState)
@ -90,7 +90,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `select and deselect a single bookmark changes the mode`() = runBlocking {
fun `select and deselect a single bookmark changes the mode`() = runTest {
val initialState = BookmarkFragmentState(tree)
val store = BookmarkFragmentStore(initialState)
@ -104,7 +104,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `selecting the same item twice does nothing`() = runBlocking {
fun `selecting the same item twice does nothing`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Selecting(setOf(item, subfolder)))
val store = BookmarkFragmentStore(initialState)
@ -114,7 +114,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `deselecting an unselected bookmark does nothing`() = runBlocking {
fun `deselecting an unselected bookmark does nothing`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Selecting(setOf(childItem)))
val store = BookmarkFragmentStore(initialState)
@ -124,7 +124,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `deselecting while not in selecting mode does nothing`() = runBlocking {
fun `deselecting while not in selecting mode does nothing`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Normal())
val store = BookmarkFragmentStore(initialState)
@ -134,7 +134,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `deselect all bookmarks changes the mode`() = runBlocking {
fun `deselect all bookmarks changes the mode`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Selecting(setOf(item, childItem)))
val store = BookmarkFragmentStore(initialState)
@ -144,7 +144,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `deselect all bookmarks when none are selected`() = runBlocking {
fun `deselect all bookmarks when none are selected`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Normal())
val store = BookmarkFragmentStore(initialState)
@ -154,7 +154,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `deleting bookmarks changes the mode`() = runBlocking {
fun `deleting bookmarks changes the mode`() = runTest {
val initialState = BookmarkFragmentState(tree, BookmarkFragmentState.Mode.Selecting(setOf(item, childItem)))
val store = BookmarkFragmentStore(initialState)
@ -167,7 +167,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `selecting and deselecting bookmarks does not affect loading state`() = runBlocking {
fun `selecting and deselecting bookmarks does not affect loading state`() = runTest {
val initialState = BookmarkFragmentState(tree, isLoading = true)
val store = BookmarkFragmentStore(initialState)
@ -182,7 +182,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `changing bookmarks disables loading state`() = runBlocking {
fun `changing bookmarks disables loading state`() = runTest {
val initialState = BookmarkFragmentState(tree, isLoading = true)
val store = BookmarkFragmentStore(initialState)
@ -191,7 +191,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `switching to Desktop Bookmarks folder sets showMenu state to false`() = runBlocking {
fun `switching to Desktop Bookmarks folder sets showMenu state to false`() = runTest {
val initialState = BookmarkFragmentState(tree)
val store = BookmarkFragmentStore(initialState)
@ -202,7 +202,7 @@ class BookmarkFragmentStoreTest {
}
@Test
fun `changing the tree or deselecting in Syncing mode should stay in Syncing mode`() = runBlocking {
fun `changing the tree or deselecting in Syncing mode should stay in Syncing mode`() = runTest {
val initialState = BookmarkFragmentState(tree)
val store = BookmarkFragmentStore(initialState)

@ -7,7 +7,7 @@ package org.mozilla.fenix.library.bookmarks
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.engine.EngineSession
import org.junit.Assert.assertTrue
import org.junit.Before
@ -26,7 +26,7 @@ class BookmarkSearchControllerTest {
}
@Test
fun `WHEN editing is cancelled THEN clearToolbarFocus is called`() = runBlockingTest {
fun `WHEN editing is cancelled THEN clearToolbarFocus is called`() = runTest {
var clearToolbarFocusInvoked = false
createController(
clearToolbarFocus = {

@ -6,7 +6,7 @@ package org.mozilla.fenix.library.bookmarks
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@ -24,7 +24,7 @@ class BookmarkSearchDialogInteractorTest {
}
@Test
fun onEditingCanceled() = runBlockingTest {
fun onEditingCanceled() = runTest {
interactor.onEditingCanceled()
verify {

@ -4,7 +4,7 @@
package org.mozilla.fenix.library.bookmarks
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Test
@ -22,7 +22,7 @@ class BookmarkSearchFragmentStoreTest {
}
@Test
fun updateQuery() = runBlocking {
fun updateQuery() = runTest {
val initialState = BookmarkSearchFragmentState(query = "")
val store = BookmarkSearchFragmentStore(initialState)
val query = "test query"

@ -8,7 +8,7 @@ import android.content.Context
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.appservices.places.BookmarkRoot
import mozilla.components.concept.storage.BookmarkNode
import mozilla.components.concept.storage.BookmarkNodeType
@ -63,7 +63,7 @@ class DesktopFoldersTest {
}
@Test
fun `withOptionalDesktopFolders other node`() = runBlocking {
fun `withOptionalDesktopFolders other node`() = runTest {
val node = basicNode.copy(guid = "12345")
val desktopFolders = DesktopFolders(context, showMobileRoot = true)

@ -7,9 +7,7 @@ package org.mozilla.fenix.library.downloads
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.components.browser.state.state.content.DownloadState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@ -27,7 +25,6 @@ class DownloadControllerTest {
contentType = "jpg",
status = DownloadState.Status.COMPLETED
)
private val scope = TestCoroutineScope()
private val store: DownloadFragmentStore = mockk(relaxed = true)
private val state: DownloadFragmentState = mockk(relaxed = true)
@ -56,11 +53,6 @@ class DownloadControllerTest {
every { store.state } returns state
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun onPressDownloadItemInNormalMode() {
controller.handleOpen(downloadItem)

@ -4,7 +4,7 @@
package org.mozilla.fenix.library.downloads
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.state.content.DownloadState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
@ -31,7 +31,7 @@ class DownloadFragmentStoreTest {
)
@Test
fun exitEditMode() = runBlocking {
fun exitEditMode() = runTest {
val initialState = oneItemEditState()
val store = DownloadFragmentStore(initialState)
@ -41,7 +41,7 @@ class DownloadFragmentStoreTest {
}
@Test
fun itemAddedForRemoval() = runBlocking {
fun itemAddedForRemoval() = runTest {
val initialState = emptyDefaultState()
val store = DownloadFragmentStore(initialState)
@ -54,7 +54,7 @@ class DownloadFragmentStoreTest {
}
@Test
fun removeItemForRemoval() = runBlocking {
fun removeItemForRemoval() = runTest {
val initialState = twoItemEditState()
val store = DownloadFragmentStore(initialState)

@ -9,12 +9,12 @@ import io.mockk.coVerifyOrder
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import org.junit.After
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.fenix.R
@ -32,7 +32,11 @@ class HistoryControllerTest {
0.toLong(),
HistoryItemTimeGroup.timeGroupForTimestamp(0)
)
private val scope = TestCoroutineScope()
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val scope = coroutinesTestRule.scope
private val store: HistoryFragmentStore = mockk(relaxed = true)
private val appStore: AppStore = mockk(relaxed = true)
private val state: HistoryFragmentState = mockk(relaxed = true)
@ -44,11 +48,6 @@ class HistoryControllerTest {
every { store.state } returns state
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun onPressHistoryItemInNormalMode() {
var actualHistoryItem: History? = null

@ -4,7 +4,7 @@
package org.mozilla.fenix.library.history
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotSame
@ -17,7 +17,7 @@ class HistoryFragmentStoreTest {
private val pendingDeletionItem = historyItem.toPendingDeletionHistory()
@Test
fun exitEditMode() = runBlocking {
fun exitEditMode() = runTest {
val initialState = oneItemEditState()
val store = HistoryFragmentStore(initialState)
@ -27,7 +27,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun itemAddedForRemoval() = runBlocking {
fun itemAddedForRemoval() = runTest {
val initialState = emptyDefaultState()
val store = HistoryFragmentStore(initialState)
@ -40,7 +40,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun removeItemForRemoval() = runBlocking {
fun removeItemForRemoval() = runTest {
val initialState = twoItemEditState()
val store = HistoryFragmentStore(initialState)
@ -50,7 +50,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun startSync() = runBlocking {
fun startSync() = runTest {
val initialState = emptyDefaultState()
val store = HistoryFragmentStore(initialState)
@ -60,7 +60,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun finishSync() = runBlocking {
fun finishSync() = runTest {
val initialState = HistoryFragmentState(
items = listOf(),
mode = HistoryFragmentState.Mode.Syncing,
@ -76,7 +76,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun changeEmptyState() = runBlocking {
fun changeEmptyState() = runTest {
val initialState = emptyDefaultState()
val store = HistoryFragmentStore(initialState)
@ -90,7 +90,7 @@ class HistoryFragmentStoreTest {
}
@Test
fun updatePendingDeletionItems() = runBlocking {
fun updatePendingDeletionItems() = runTest {
val initialState = emptyDefaultState()
val store = HistoryFragmentStore(initialState)

@ -7,7 +7,7 @@ package org.mozilla.fenix.library.history
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.engine.EngineSession
import mozilla.components.support.test.robolectric.testContext
import mozilla.telemetry.glean.testing.GleanTestRule
@ -38,7 +38,7 @@ class HistorySearchControllerTest {
}
@Test
fun `WHEN editing is cancelled THEN clearToolbarFocus is called`() = runBlockingTest {
fun `WHEN editing is cancelled THEN clearToolbarFocus is called`() = runTest {
var clearToolbarFocusInvoked = false
createController(
clearToolbarFocus = {

@ -6,7 +6,7 @@ package org.mozilla.fenix.library.history
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@ -24,7 +24,7 @@ class HistorySearchDialogInteractorTest {
}
@Test
fun onEditingCanceled() = runBlockingTest {
fun onEditingCanceled() = runTest {
interactor.onEditingCanceled()
verify {

@ -5,7 +5,7 @@
package org.mozilla.fenix.library.history
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Test
@ -26,7 +26,7 @@ class HistorySearchFragmentStoreTest {
}
@Test
fun updateQuery() = runBlocking {
fun updateQuery() = runTest {
val initialState = HistorySearchFragmentState(query = "")
val store = HistorySearchFragmentStore(initialState)
val query = "test query"

@ -4,7 +4,7 @@
package org.mozilla.fenix.library.historymetadata
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.storage.HistoryMetadataKey
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@ -52,7 +52,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test updating the items in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test updating the items in HistoryMetadataGroupFragmentStore`() = runTest {
assertEquals(0, store.state.items.size)
val items = listOf(mozillaHistoryMetadataItem, firefoxHistoryMetadataItem)
@ -62,7 +62,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test selecting and deselecting an item in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test selecting and deselecting an item in HistoryMetadataGroupFragmentStore`() = runTest {
val items = listOf(mozillaHistoryMetadataItem, firefoxHistoryMetadataItem)
store.dispatch(HistoryMetadataGroupFragmentAction.UpdateHistoryItems(items)).join()
@ -82,7 +82,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test deselecting all items in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test deselecting all items in HistoryMetadataGroupFragmentStore`() = runTest {
val items = listOf(mozillaHistoryMetadataItem, firefoxHistoryMetadataItem)
store.dispatch(HistoryMetadataGroupFragmentAction.UpdateHistoryItems(items)).join()
@ -94,7 +94,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test deleting an item in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test deleting an item in HistoryMetadataGroupFragmentStore`() = runTest {
val items = listOf(mozillaHistoryMetadataItem, firefoxHistoryMetadataItem)
store.dispatch(HistoryMetadataGroupFragmentAction.UpdateHistoryItems(items)).join()
@ -105,7 +105,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test deleting all items in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test deleting all items in HistoryMetadataGroupFragmentStore`() = runTest {
val items = listOf(mozillaHistoryMetadataItem, firefoxHistoryMetadataItem)
store.dispatch(HistoryMetadataGroupFragmentAction.UpdateHistoryItems(items)).join()
@ -115,7 +115,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test changing the empty state of HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test changing the empty state of HistoryMetadataGroupFragmentStore`() = runTest {
store.dispatch(HistoryMetadataGroupFragmentAction.ChangeEmptyState(false)).join()
assertFalse(store.state.isEmpty)
@ -124,7 +124,7 @@ class HistoryMetadataGroupFragmentStoreTest {
}
@Test
fun `Test updating pending deletion items in HistoryMetadataGroupFragmentStore`() = runBlocking {
fun `Test updating pending deletion items in HistoryMetadataGroupFragmentStore`() = runTest {
store.dispatch(HistoryMetadataGroupFragmentAction.UpdatePendingDeletionItems(setOf(pendingDeletionItem))).join()
assertEquals(setOf(pendingDeletionItem), store.state.pendingDeletionItems)

@ -11,8 +11,6 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.browser.state.action.HistoryMetadataAction
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.browser.storage.sync.PlacesHistoryStorage
@ -22,7 +20,7 @@ import mozilla.components.feature.tabs.TabsUseCases
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@ -51,8 +49,7 @@ class HistoryMetadataGroupControllerTest {
val gleanTestRule = GleanTestRule(testContext)
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val scope = TestCoroutineScope(testDispatcher)
private val scope = coroutinesTestRule.scope
private val activity: HomeActivity = mockk(relaxed = true)
private val context: Context = mockk(relaxed = true)
@ -114,11 +111,6 @@ class HistoryMetadataGroupControllerTest {
every { store.state.items } returns getMetadataItemsList()
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun handleOpen() {
assertFalse(GleanHistory.searchTermGroupOpenTab.testHasValue())
@ -195,7 +187,7 @@ class HistoryMetadataGroupControllerTest {
}
@Test
fun handleDeleteSingle() = testDispatcher.runBlockingTest {
fun handleDeleteSingle() = runTestOnMain {
assertFalse(GleanHistory.searchTermGroupRemoveTab.testHasValue())
controller.handleDelete(setOf(mozillaHistoryMetadataItem))
@ -223,7 +215,7 @@ class HistoryMetadataGroupControllerTest {
}
@Test
fun handleDeleteMultiple() = testDispatcher.runBlockingTest {
fun handleDeleteMultiple() = runTestOnMain {
assertFalse(GleanHistory.searchTermGroupRemoveTab.testHasValue())
controller.handleDelete(getMetadataItemsList().toSet())
@ -248,7 +240,7 @@ class HistoryMetadataGroupControllerTest {
}
@Test
fun handleDeleteAbnormal() = testDispatcher.runBlockingTest {
fun handleDeleteAbnormal() = runTestOnMain {
val abnormalList = listOf(
mozillaHistoryMetadataItem,
firefoxHistoryMetadataItem,
@ -292,7 +284,7 @@ class HistoryMetadataGroupControllerTest {
}
@Test
fun handleDeleteAll() = testDispatcher.runBlockingTest {
fun handleDeleteAll() = runTestOnMain {
assertFalse(GleanHistory.searchTermGroupRemoveAll.testHasValue())
controller.handleDeleteAll()

@ -15,7 +15,8 @@ import io.mockk.just
import io.mockk.Runs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.action.RecentlyClosedAction
import mozilla.components.browser.state.state.recover.TabState
import mozilla.components.browser.state.store.BrowserStore
@ -245,11 +246,12 @@ class DefaultRecentlyClosedControllerTest {
}
@Test
fun handleRestore() = runBlocking {
fun handleRestore() = runTest {
val item: TabState = mockk(relaxed = true)
assertFalse(RecentlyClosedTabs.openTab.testHasValue())
createController(scope = this).handleRestore(item)
runCurrent()
coVerify { tabsUseCases.restore.invoke(eq(item), any(), true) }
assertTrue(RecentlyClosedTabs.openTab.testHasValue())

@ -5,7 +5,7 @@
package org.mozilla.fenix.nimbus
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@ -25,7 +25,7 @@ class NimbusBranchesStoreTest {
}
@Test
fun `GIVEN a new branch and selected branch WHEN UpdateBranches action is dispatched THEN state is updated`() = runBlocking {
fun `GIVEN a new branch and selected branch WHEN UpdateBranches action is dispatched THEN state is updated`() = runTest {
assertTrue(nimbusBranchesStore.state.isLoading)
val branches: List<Branch> = listOf(mockk(), mockk())
@ -40,7 +40,7 @@ class NimbusBranchesStoreTest {
}
@Test
fun `GIVEN a new selected branch WHEN UpdateSelectedBranch action is dispatched THEN selectedBranch state is updated`() = runBlocking {
fun `GIVEN a new selected branch WHEN UpdateSelectedBranch action is dispatched THEN selectedBranch state is updated`() = runTest {
assertEquals("", nimbusBranchesStore.state.selectedBranch)
val selectedBranch = "control"

@ -17,8 +17,9 @@ import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkStatic
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.engine.Engine
import mozilla.components.concept.engine.webpush.WebPushDelegate
import mozilla.components.concept.engine.webpush.WebPushHandler
@ -38,7 +39,7 @@ import org.mozilla.fenix.helpers.MockkRetryTestRule
class WebPushEngineIntegrationTest {
private val scope = TestCoroutineScope()
private val scope = TestScope(UnconfinedTestDispatcher())
@MockK private lateinit var engine: Engine
@MockK private lateinit var pushFeature: AutoPushFeature
@MockK(relaxed = true) private lateinit var handler: WebPushHandler
@ -65,11 +66,10 @@ class WebPushEngineIntegrationTest {
@After
fun teardown() {
unmockkStatic(Base64::class)
scope.cleanupTestCoroutines()
}
@Test
fun `methods are no-op before calling start`() = scope.runBlockingTest {
fun `methods are no-op before calling start`() = scope.runTest {
integration.onMessageReceived("push", null)
integration.onSubscriptionChanged("push")
verify { handler wasNot Called }

@ -17,7 +17,7 @@ import io.mockk.mockkObject
import io.mockk.spyk
import io.mockk.unmockkObject
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.action.BrowserAction
import mozilla.components.browser.state.action.TabListAction
import mozilla.components.browser.state.search.SearchEngine
@ -184,7 +184,7 @@ class SearchDialogControllerTest {
}
@Test
fun handleEditingCancelled() = runBlockingTest {
fun handleEditingCancelled() = runTest {
var clearToolbarFocusInvoked = false
createController(
clearToolbarFocus = {

@ -6,7 +6,7 @@ package org.mozilla.fenix.search
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.search.SearchEngine
import org.junit.Before
import org.junit.Test
@ -35,7 +35,7 @@ class SearchDialogInteractorTest {
}
@Test
fun onEditingCanceled() = runBlockingTest {
fun onEditingCanceled() = runTest {
interactor.onEditingCanceled()
verify {

@ -8,7 +8,7 @@ import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.search.RegionState
import mozilla.components.browser.state.search.SearchEngine
import mozilla.components.browser.state.state.BrowserState
@ -141,7 +141,7 @@ class SearchFragmentStoreTest {
}
@Test
fun updateQuery() = runBlocking {
fun updateQuery() = runTest {
val initialState = emptyDefaultState()
val store = SearchFragmentStore(initialState)
val query = "test query"
@ -152,7 +152,7 @@ class SearchFragmentStoreTest {
}
@Test
fun selectSearchShortcutEngine() = runBlocking {
fun selectSearchShortcutEngine() = runTest {
val initialState = emptyDefaultState()
val store = SearchFragmentStore(initialState)
@ -163,7 +163,7 @@ class SearchFragmentStoreTest {
}
@Test
fun showSearchShortcutEnginePicker() = runBlocking {
fun showSearchShortcutEnginePicker() = runTest {
val initialState = emptyDefaultState()
val store = SearchFragmentStore(initialState)
@ -173,7 +173,7 @@ class SearchFragmentStoreTest {
}
@Test
fun showSearchSuggestions() = runBlocking {
fun showSearchSuggestions() = runTest {
val initialState = emptyDefaultState()
val store = SearchFragmentStore(initialState)
@ -186,7 +186,7 @@ class SearchFragmentStoreTest {
}
@Test
fun allowSearchInPrivateMode() = runBlocking {
fun allowSearchInPrivateMode() = runTest {
val initialState = emptyDefaultState()
val store = SearchFragmentStore(initialState)
@ -213,7 +213,7 @@ class SearchFragmentStoreTest {
}
@Test
fun `Updating SearchFragmentState from SearchState`() = runBlocking {
fun `Updating SearchFragmentState from SearchState`() = runTest {
val store = SearchFragmentStore(
emptyDefaultState(
searchEngineSource = SearchEngineSource.None,
@ -270,7 +270,7 @@ class SearchFragmentStoreTest {
}
@Test
fun `Updating SearchFragmentState from SearchState - shortcuts disabled`() = runBlocking {
fun `Updating SearchFragmentState from SearchState - shortcuts disabled`() = runTest {
val store = SearchFragmentStore(
emptyDefaultState(
searchEngineSource = SearchEngineSource.None,

@ -10,7 +10,7 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkStatic
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.search.SearchEngine
import mozilla.components.browser.state.state.BrowserState
import mozilla.components.browser.state.state.SearchState
@ -42,7 +42,7 @@ class ShortcutsSuggestionProviderTest {
}
@Test
fun `returns suggestions from search engine provider`() = runBlockingTest {
fun `returns suggestions from search engine provider`() = runTest {
val engineOne = mockk<SearchEngine> {
every { id } returns "1"
every { name } returns "EngineOne"
@ -82,7 +82,7 @@ class ShortcutsSuggestionProviderTest {
}
@Test
fun `callbacks are triggered when suggestions are clicked`() = runBlockingTest {
fun `callbacks are triggered when suggestions are clicked`() = runTest {
val engineOne = mockk<SearchEngine>(relaxed = true)
val store = BrowserStore(
BrowserState(

@ -9,10 +9,12 @@ import androidx.preference.Preference
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.concept.fetch.Client
import mozilla.components.service.nimbus.NimbusDisabled
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
@ -38,7 +40,6 @@ class SettingsFragmentTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val settingsFragment = SettingsFragment()
@Before
@ -64,7 +65,7 @@ class SettingsFragmentTest {
}
@Test
fun `Add-on collection override pref is visible if debug menu active`() {
fun `Add-on collection override pref is visible if debug menu active`() = runTestOnMain {
val settingsFragment = SettingsFragment()
val activity = Robolectric.buildActivity(FragmentActivity::class.java).create().get()
@ -72,7 +73,7 @@ class SettingsFragmentTest {
.add(settingsFragment, "test")
.commitNow()
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val preferenceAmoCollectionOverride = settingsFragment.findPreference<Preference>(
settingsFragment.getPreferenceKey(R.string.pref_key_override_amo_collection)
@ -89,7 +90,7 @@ class SettingsFragmentTest {
}
@Test
fun `Add-on collection override pref is visible if already configured`() {
fun `Add-on collection override pref is visible if already configured`() = runTestOnMain {
val settingsFragment = SettingsFragment()
val activity = Robolectric.buildActivity(FragmentActivity::class.java).create().get()
@ -97,7 +98,7 @@ class SettingsFragmentTest {
.add(settingsFragment, "test")
.commitNow()
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
val preferenceAmoCollectionOverride = settingsFragment.findPreference<Preference>(
settingsFragment.getPreferenceKey(R.string.pref_key_override_amo_collection)

@ -4,7 +4,7 @@
package org.mozilla.fenix.settings.account
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Test
@ -12,7 +12,7 @@ import org.junit.Test
class AccountSettingsFragmentStoreTest {
@Test
fun syncFailed() = runBlocking {
fun syncFailed() = runTest {
val initialState = AccountSettingsFragmentState()
val store = AccountSettingsFragmentStore(initialState)
val duration = 1L
@ -23,7 +23,7 @@ class AccountSettingsFragmentStoreTest {
}
@Test
fun syncEnded() = runBlocking {
fun syncEnded() = runTest {
val initialState = AccountSettingsFragmentState()
val store = AccountSettingsFragmentStore(initialState)
val duration = 1L
@ -34,7 +34,7 @@ class AccountSettingsFragmentStoreTest {
}
@Test
fun signOut() = runBlocking {
fun signOut() = runTest {
val initialState = AccountSettingsFragmentState()
val store = AccountSettingsFragmentStore(initialState)
val deviceName = "testing"

@ -11,12 +11,11 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.concept.storage.Address
import mozilla.components.concept.storage.UpdatableAddressFields
import mozilla.components.service.sync.autofill.AutofillCreditCardsAddressesStorage
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ -28,7 +27,6 @@ class DefaultAddressEditorControllerTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testCoroutineScope = TestCoroutineScope()
private lateinit var controller: DefaultAddressEditorController
@ -37,7 +35,7 @@ class DefaultAddressEditorControllerTest {
controller = spyk(
DefaultAddressEditorController(
storage = storage,
lifecycleScope = testCoroutineScope,
lifecycleScope = coroutinesTestRule.scope,
navController = navController,
)
)
@ -53,7 +51,7 @@ class DefaultAddressEditorControllerTest {
}
@Test
fun `GIVEN a new address record WHEN save address is called THEN save the new address record to storage`() = testCoroutineScope.runBlockingTest {
fun `GIVEN a new address record WHEN save address is called THEN save the new address record to storage`() = runTestOnMain {
val addressFields = UpdatableAddressFields(
givenName = "John",
additionalName = "",
@ -78,7 +76,7 @@ class DefaultAddressEditorControllerTest {
}
@Test
fun `GIVEN an existing address record WHEN save address is called THEN update the address record to storage`() = runBlockingTest {
fun `GIVEN an existing address record WHEN save address is called THEN update the address record to storage`() = runTestOnMain {
val address: Address = mockk()
val addressFields: UpdatableAddressFields = mockk()
every { address.guid } returns "123"

@ -4,7 +4,7 @@
package org.mozilla.fenix.settings.advanced
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@ -29,14 +29,14 @@ class LocaleSettingsStoreTest {
}
@Test
fun `change selected locale`() = runBlocking {
fun `change selected locale`() = runTest {
localeSettingsStore.dispatch(LocaleSettingsAction.Select(otherLocale)).join()
assertEquals(otherLocale, localeSettingsStore.state.selectedLocale)
}
@Test
fun `change selected list by search query`() = runBlocking {
fun `change selected list by search query`() = runTest {
localeSettingsStore.dispatch(LocaleSettingsAction.Search("Eng")).join()
assertEquals(2, (localeSettingsStore.state.searchedLocaleList as ArrayList).size)

@ -5,7 +5,7 @@
package org.mozilla.fenix.settings.autofill
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.storage.Address
import mozilla.components.concept.storage.CreditCard
import org.junit.Assert.assertEquals
@ -26,7 +26,7 @@ class AutofillFragmentStoreTest {
}
@Test
fun testUpdateCreditCards() = runBlocking {
fun testUpdateCreditCards() = runTest {
assertTrue(store.state.isLoading)
val creditCards: List<CreditCard> = listOf(mockk(), mockk())
@ -37,7 +37,7 @@ class AutofillFragmentStoreTest {
}
@Test
fun `GIVEN a list of addresses WHEN update addresses action is dispatched THEN addresses state is updated`() = runBlocking {
fun `GIVEN a list of addresses WHEN update addresses action is dispatched THEN addresses state is updated`() = runTest {
assertTrue(store.state.isLoading)
val addresses: List<Address> = listOf(mockk(), mockk())

@ -10,14 +10,17 @@ import androidx.preference.Preference
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.concept.storage.Address
import mozilla.components.concept.storage.CreditCard
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.fenix.R
@ -29,12 +32,14 @@ import org.robolectric.Robolectric
@RunWith(FenixRobolectricTestRunner::class)
class AutofillSettingFragmentTest {
private val testDispatcher = TestCoroutineDispatcher()
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private lateinit var autofillSettingFragment: AutofillSettingFragment
private val navController: NavController = mockk(relaxed = true)
@Before
fun setUp() {
fun setUp() = runTestOnMain {
every { testContext.components.settings } returns mockk(relaxed = true)
every { testContext.components.settings.addressFeature } returns true
every { testContext.components.settings.shouldAutofillCreditCardDetails } returns true
@ -46,11 +51,11 @@ class AutofillSettingFragmentTest {
activity.supportFragmentManager.beginTransaction()
.add(autofillSettingFragment, "CreditCardsSettingFragmentTest")
.commitNow()
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
}
@Test
fun `GIVEN the list of credit cards is not empty, WHEN fragment is displayed THEN the manage credit cards pref is 'Manage saved cards'`() {
fun `GIVEN the list of credit cards is not empty, WHEN fragment is displayed THEN the manage credit cards pref is 'Manage saved cards'`() = runTestOnMain {
val preferenceTitle =
testContext.getString(R.string.preferences_credit_cards_manage_saved_cards)
val manageCardsPreference = autofillSettingFragment.findPreference<Preference>(
@ -72,7 +77,7 @@ class AutofillSettingFragmentTest {
}
@Test
fun `GIVEN the list of credit cards is empty, WHEN fragment is displayed THEN the manage credit cards pref is 'Add card'`() {
fun `GIVEN the list of credit cards is empty, WHEN fragment is displayed THEN the manage credit cards pref is 'Add card'`() = runTestOnMain {
val preferenceTitle =
testContext.getString(R.string.preferences_credit_cards_add_credit_card)
val manageCardsPreference = autofillSettingFragment.findPreference<Preference>(
@ -100,7 +105,7 @@ class AutofillSettingFragmentTest {
}
@Test
fun `GIVEN the list of addresses is not empty WHEN fragment is displayed THEN the manage addresses preference label is 'Manage addresses'`() {
fun `GIVEN the list of addresses is not empty WHEN fragment is displayed THEN the manage addresses preference label is 'Manage addresses'`() = runTestOnMain {
val preferenceTitle =
testContext.getString(R.string.preferences_addresses_manage_addresses)
val manageAddressesPreference = autofillSettingFragment.findPreference<Preference>(
@ -131,7 +136,7 @@ class AutofillSettingFragmentTest {
}
@Test
fun `GIVEN the list of addresses is empty WHEN fragment is displayed THEN the manage addresses preference label is 'Add address'`() {
fun `GIVEN the list of addresses is empty WHEN fragment is displayed THEN the manage addresses preference label is 'Add address'`() = runTestOnMain {
val preferenceTitle =
testContext.getString(R.string.preferences_addresses_add_address)
val manageAddressesPreference = autofillSettingFragment.findPreference<Preference>(

@ -6,7 +6,7 @@ package org.mozilla.fenix.settings.creditcards
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.storage.CreditCard
import mozilla.components.concept.storage.CreditCardNumber
import mozilla.components.service.sync.autofill.AutofillCreditCardsAddressesStorage
@ -37,7 +37,7 @@ class CreditCardEditorStateTest {
)
@Test
fun testToCreditCardEditorState() = runBlocking {
fun testToCreditCardEditorState() = runTest {
val storage: AutofillCreditCardsAddressesStorage = mockk(relaxed = true)
val crypto: AutofillCrypto = mockk(relaxed = true)

@ -10,7 +10,7 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.concept.storage.CreditCard
import mozilla.components.concept.storage.CreditCardNumber
import mozilla.components.concept.storage.NewCreditCardFields
@ -103,7 +103,7 @@ class CreditCardEditorViewTest {
}
@Test
fun `GIVEN a credit card THEN credit card form inputs are displaying the provided credit card information`() = runBlocking {
fun `GIVEN a credit card THEN credit card form inputs are displaying the provided credit card information`() = runTest {
creditCardEditorView.bind(creditCard.toCreditCardEditorState(storage))
assertEquals(cardNumber, fragmentCreditCardEditorBinding.cardNumberInput.text.toString())
@ -124,7 +124,7 @@ class CreditCardEditorViewTest {
}
@Test
fun `GIVEN a credit card WHEN the delete card button is clicked THEN interactor is called`() = runBlocking {
fun `GIVEN a credit card WHEN the delete card button is clicked THEN interactor is called`() = runTest {
creditCardEditorView.bind(creditCard.toCreditCardEditorState(storage))
assertEquals(View.VISIBLE, fragmentCreditCardEditorBinding.deleteButton.visibility)
@ -324,7 +324,7 @@ class CreditCardEditorViewTest {
}
@Test
fun `GIVEN a valid credit card WHEN the save button is clicked THEN interactor is called`() = runBlocking {
fun `GIVEN a valid credit card WHEN the save button is clicked THEN interactor is called`() = runTest {
creditCardEditorView.bind(creditCard.toCreditCardEditorState(storage))
fragmentCreditCardEditorBinding.saveButton.performClick()

@ -11,17 +11,15 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.concept.storage.CreditCardNumber
import mozilla.components.concept.storage.NewCreditCardFields
import mozilla.components.concept.storage.UpdatableCreditCardFields
import mozilla.components.service.sync.autofill.AutofillCreditCardsAddressesStorage
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import mozilla.components.support.utils.CreditCardNetworkType
import mozilla.telemetry.glean.testing.GleanTestRule
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
@ -47,7 +45,7 @@ class DefaultCreditCardEditorControllerTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val testCoroutineScope = TestCoroutineScope(testDispatcher)
private val testCoroutineScope = coroutinesTestRule.scope
@Before
fun setup() {
@ -68,11 +66,6 @@ class DefaultCreditCardEditorControllerTest {
)
}
@After
fun cleanUp() {
testCoroutineScope.cleanupTestCoroutines()
}
@Test
fun handleCancelButtonClicked() {
controller.handleCancelButtonClicked()
@ -83,7 +76,7 @@ class DefaultCreditCardEditorControllerTest {
}
@Test
fun handleDeleteCreditCard() = testCoroutineScope.runBlockingTest {
fun handleDeleteCreditCard() = runTestOnMain {
val creditCardId = "id"
assertFalse(CreditCards.deleted.testHasValue())
@ -97,7 +90,7 @@ class DefaultCreditCardEditorControllerTest {
}
@Test
fun handleSaveCreditCard() = testCoroutineScope.runBlockingTest {
fun handleSaveCreditCard() = runTestOnMain {
val creditCardFields = NewCreditCardFields(
billingName = "Banana Apple",
plaintextCardNumber = CreditCardNumber.Plaintext("4111111111111112"),
@ -118,7 +111,7 @@ class DefaultCreditCardEditorControllerTest {
}
@Test
fun handleUpdateCreditCard() = testCoroutineScope.runBlockingTest {
fun handleUpdateCreditCard() = runTestOnMain {
val creditCardId = "id"
val creditCardFields = UpdatableCreditCardFields(
billingName = "Banana Apple",

@ -10,8 +10,6 @@ import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope.coroutineContext
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.browser.icons.BrowserIcons
import mozilla.components.browser.state.action.EngineAction
import mozilla.components.browser.state.action.RecentlyClosedAction
@ -21,6 +19,7 @@ import mozilla.components.concept.storage.HistoryStorage
import mozilla.components.feature.downloads.DownloadsUseCases
import mozilla.components.feature.tabs.TabsUseCases
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ -52,12 +51,12 @@ class DefaultDeleteBrowsingDataControllerTest {
permissionStorage = permissionStorage,
iconsStorage = iconsStorage,
engine = engine,
coroutineContext = coroutineContext
coroutineContext = coroutinesTestRule.testDispatcher
)
}
@Test
fun deleteTabs() = runBlockingTest {
fun deleteTabs() = runTestOnMain {
controller.deleteTabs()
@ -67,7 +66,7 @@ class DefaultDeleteBrowsingDataControllerTest {
}
@Test
fun deleteBrowsingData() = runBlockingTest {
fun deleteBrowsingData() = runTestOnMain {
controller = spyk(controller)
controller.deleteBrowsingData()
@ -81,7 +80,7 @@ class DefaultDeleteBrowsingDataControllerTest {
}
@Test
fun deleteCookies() = runBlockingTest {
fun deleteCookies() = runTestOnMain {
controller.deleteCookies()
verify {
@ -95,7 +94,7 @@ class DefaultDeleteBrowsingDataControllerTest {
}
@Test
fun deleteCachedFiles() = runBlockingTest {
fun deleteCachedFiles() = runTestOnMain {
controller.deleteCachedFiles()
@ -105,7 +104,7 @@ class DefaultDeleteBrowsingDataControllerTest {
}
@Test
fun deleteSitePermissions() = runBlockingTest {
fun deleteSitePermissions() = runTestOnMain {
controller.deleteSitePermissions()
coVerify {
@ -115,7 +114,7 @@ class DefaultDeleteBrowsingDataControllerTest {
}
@Test
fun deleteDownloads() = runBlockingTest {
fun deleteDownloads() = runTestOnMain {
controller.deleteDownloads()

@ -11,14 +11,14 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.verifyOrder
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.icons.BrowserIcons
import mozilla.components.browser.storage.sync.PlacesHistoryStorage
import mozilla.components.concept.engine.Engine
import mozilla.components.feature.downloads.DownloadsUseCases.RemoveAllDownloadsUseCase
import mozilla.components.feature.tabs.TabsUseCases
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
@ -27,12 +27,12 @@ import org.mozilla.fenix.HomeActivity
import org.mozilla.fenix.components.FenixSnackbar
import org.mozilla.fenix.components.PermissionStorage
import org.mozilla.fenix.ext.components
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.TABS
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.CACHE
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.COOKIES
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.DOWNLOADS
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.PERMISSIONS
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.HISTORY
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.PERMISSIONS
import org.mozilla.fenix.settings.deletebrowsingdata.DeleteBrowsingDataOnQuitType.TABS
import org.mozilla.fenix.utils.Settings
@OptIn(ExperimentalCoroutinesApi::class)
@ -64,20 +64,15 @@ class DeleteAndQuitTest {
every { activity.components.core.icons } returns iconsStorage
}
@After
fun cleanUp() {
coroutinesTestRule.testDispatcher.cleanupTestCoroutines()
}
@Ignore("Failing test; need more investigation.")
@Test
fun `delete only tabs and quit`() = runBlockingTest {
fun `delete only tabs and quit`() = runTestOnMain {
// When
every { settings.getDeleteDataOnQuit(TABS) } returns true
deleteAndQuit(activity, this, snackbar)
coroutinesTestRule.testDispatcher.advanceUntilIdle()
advanceUntilIdle()
verifyOrder {
snackbar.show()
@ -105,7 +100,7 @@ class DeleteAndQuitTest {
@Ignore("Failing test; need more investigation.")
@Test
fun `delete everything and quit`() = runBlockingTest {
fun `delete everything and quit`() = runTestOnMain {
// When
every { settings.getDeleteDataOnQuit(TABS) } returns true
every { settings.getDeleteDataOnQuit(HISTORY) } returns true
@ -116,7 +111,7 @@ class DeleteAndQuitTest {
deleteAndQuit(activity, this, snackbar)
coroutinesTestRule.testDispatcher.advanceUntilIdle()
advanceUntilIdle()
coVerify(exactly = 1) {
snackbar.show()

@ -10,15 +10,13 @@ import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.concept.storage.EncryptedLogin
import mozilla.components.concept.storage.Login
import mozilla.components.concept.storage.LoginEntry
import mozilla.components.service.sync.logins.InvalidRecordException
import mozilla.components.service.sync.logins.SyncableLoginsStorage
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ -34,7 +32,7 @@ class SavedLoginsStorageControllerTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val ioDispatcher = coroutinesTestRule.testDispatcher
private val scope = TestCoroutineScope(ioDispatcher)
private val scope = coroutinesTestRule.scope
private val passwordsStorage: SyncableLoginsStorage = mockk(relaxed = true)
private lateinit var controller: SavedLoginsStorageController
@ -59,13 +57,8 @@ class SavedLoginsStorageControllerTest {
)
}
@After
fun cleanUp() {
scope.cleanupTestCoroutines()
}
@Test
fun `WHEN a login is deleted, THEN navigate back to the previous page`() = scope.runBlockingTest {
fun `WHEN a login is deleted, THEN navigate back to the previous page`() = runTestOnMain {
val loginId = "id"
coEvery { passwordsStorage.delete(any()) } returns true
controller.delete(loginId)
@ -77,7 +70,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN fetching the login list, THEN update the state in the store`() = scope.runBlockingTest {
fun `WHEN fetching the login list, THEN update the state in the store`() = runTestOnMain {
val login = Login(
guid = "id",
origin = "https://www.test.co.gov.org",
@ -103,7 +96,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN saving an update to an item, THEN navigate to login detail view`() = scope.runBlockingTest {
fun `WHEN saving an update to an item, THEN navigate to login detail view`() = runTestOnMain {
val oldLogin = Login(
guid = "id",
origin = "https://www.test.co.gov.org",
@ -154,7 +147,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN login dupe is found for save, THEN update duplicate in the store`() = scope.runBlockingTest {
fun `WHEN login dupe is found for save, THEN update duplicate in the store`() = runTestOnMain {
val login = Login(
guid = "id",
origin = "https://www.test.co.gov.org",
@ -199,7 +192,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN login dupe is not found for save, THEN update duplicate in the store`() = scope.runBlockingTest {
fun `WHEN login dupe is not found for save, THEN update duplicate in the store`() = runTestOnMain {
val login = Login(
guid = "id",
origin = "https://www.test.co.gov.org",
@ -235,7 +228,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN login dupe is found for add, THEN update duplicate in the store`() = scope.runBlockingTest {
fun `WHEN login dupe is found for add, THEN update duplicate in the store`() = runTestOnMain {
val login = Login(
guid = "id",
origin = "https://www.test.co.gov.org",
@ -269,7 +262,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN login dupe is not found for add, THEN update duplicate in the store`() = scope.runBlockingTest {
fun `WHEN login dupe is not found for add, THEN update duplicate in the store`() = runTestOnMain {
coEvery {
passwordsStorage.findLoginToUpdate(any())
} returns null
@ -295,7 +288,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN findLoginToUpdate throws THEN update duplicate in the store`() = scope.runBlockingTest {
fun `WHEN findLoginToUpdate throws THEN update duplicate in the store`() = runTestOnMain {
coEvery {
passwordsStorage.findLoginToUpdate(any())
} throws InvalidRecordException("InvalidOrigin")
@ -321,7 +314,7 @@ class SavedLoginsStorageControllerTest {
}
@Test
fun `WHEN dupe checking THEN always use a non-blank password`() = scope.runBlockingTest {
fun `WHEN dupe checking THEN always use a non-blank password`() = runTestOnMain {
// If the user hasn't entered a password yet, we should use a dummy
// password to send a valid login entry to findLoginToUpdate()

@ -11,7 +11,7 @@ import io.mockk.MockKAnnotations
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verifyOrder
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.TestScope
import mozilla.components.support.test.robolectric.testContext
import org.junit.Before
import org.junit.Test
@ -25,7 +25,6 @@ class ClearSiteDataViewTest {
private lateinit var binding: QuicksettingsClearSiteDataBinding
private lateinit var interactor: ClearSiteDataViewInteractor
private lateinit var navController: NavController
private val coroutinesScope = TestCoroutineScope()
@Before
fun setup() {
@ -35,7 +34,7 @@ class ClearSiteDataViewTest {
view = spyk(
ClearSiteDataView(
testContext,
coroutinesScope,
TestScope(),
FrameLayout(testContext),
View(testContext),
interactor,

@ -15,8 +15,7 @@ import io.mockk.just
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.browser.state.state.BrowserState
import mozilla.components.browser.state.state.TabSessionState
import mozilla.components.browser.state.state.createTab
@ -28,7 +27,8 @@ import mozilla.components.feature.session.SessionUseCases
import mozilla.components.feature.session.TrackingProtectionUseCases
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import org.junit.After
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@ -57,7 +57,6 @@ class DefaultQuickSettingsControllerTest {
@MockK
private lateinit var store: QuickSettingsFragmentStore
private val coroutinesScope = TestCoroutineScope()
@MockK(relaxed = true)
private lateinit var navController: NavController
@ -85,6 +84,10 @@ class DefaultQuickSettingsControllerTest {
@get:Rule
val gleanRule = GleanTestRule(testContext)
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val scope = coroutinesTestRule.scope
@Before
fun setUp() {
MockKAnnotations.init(this)
@ -99,7 +102,7 @@ class DefaultQuickSettingsControllerTest {
quickSettingsStore = store,
browserStore = browserStore,
sessionId = tab.id,
ioScope = coroutinesScope,
ioScope = scope,
navController = navController,
sitePermissions = sitePermissions,
settings = appSettings,
@ -112,13 +115,8 @@ class DefaultQuickSettingsControllerTest {
)
}
@After
fun cleanUp() {
coroutinesScope.cleanupTestCoroutines()
}
@Test
fun `handlePermissionsShown should delegate to an injected parameter`() {
fun `handlePermissionsShown should delegate to an injected parameter`() = runTestOnMain {
every { testContext.components.core.engine } returns mockk(relaxed = true)
var displayPermissionsInvoked = false
createController(
@ -131,7 +129,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handlePermissionToggled blocked by Android should handleAndroidPermissionRequest`() {
fun `handlePermissionToggled blocked by Android should handleAndroidPermissionRequest`() = runTestOnMain {
val cameraFeature = PhoneFeature.CAMERA
val websitePermission = mockk<WebsitePermission>()
every { websitePermission.phoneFeature } returns cameraFeature
@ -145,7 +143,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handlePermissionToggled allowed by Android should toggle the permissions and modify View's state`() {
fun `handlePermissionToggled allowed by Android should toggle the permissions and modify View's state`() = runTestOnMain {
val websitePermission = mockk<WebsitePermission>()
every { websitePermission.phoneFeature } returns PhoneFeature.CAMERA
every { websitePermission.isBlockedByAndroid } returns false
@ -169,14 +167,14 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handlePermissionToggled blocked by user should navigate to site permission manager`() {
fun `handlePermissionToggled blocked by user should navigate to site permission manager`() = runTestOnMain {
every { testContext.components.core.engine } returns mockk(relaxed = true)
val websitePermission = mockk<WebsitePermission>()
val invalidSitePermissionsController = DefaultQuickSettingsController(
context = context,
quickSettingsStore = store,
browserStore = BrowserStore(),
ioScope = coroutinesScope,
ioScope = scope,
navController = navController,
sessionId = "123",
sitePermissions = null,
@ -205,7 +203,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleAutoplayChanged will add autoplay permission`() {
fun `handleAutoplayChanged will add autoplay permission`() = runTestOnMain {
val autoplayValue = mockk<AutoplayValue.AllowAll>(relaxed = true)
every { store.dispatch(any()) } returns mockk()
@ -222,7 +220,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleAutoplayChanged will update autoplay permission`() {
fun `handleAutoplayChanged will update autoplay permission`() = runTestOnMain {
val autoplayValue = mockk<AutoplayValue.AllowAll>(relaxed = true)
every { store.dispatch(any()) } returns mockk()
@ -239,7 +237,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleAndroidPermissionGranted should update the View's state`() {
fun `handleAndroidPermissionGranted should update the View's state`() = runTestOnMain {
val featureGranted = PhoneFeature.CAMERA
val permissionStatus = featureGranted.getActionLabel(context, sitePermissions, appSettings)
val permissionEnabled =
@ -261,7 +259,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleAndroidPermissionRequest should request from the injected callback`() {
fun `handleAndroidPermissionRequest should request from the injected callback`() = runTestOnMain {
every { testContext.components.core.engine } returns mockk(relaxed = true)
val testPermissions = arrayOf("TestPermission")
@ -278,7 +276,7 @@ class DefaultQuickSettingsControllerTest {
@Test
fun `handlePermissionsChange should store the updated permission and reload webpage`() =
coroutinesScope.runBlockingTest {
runTestOnMain {
val testPermissions = mockk<SitePermissions>()
controller.handlePermissionsChange(testPermissions)
@ -292,7 +290,7 @@ class DefaultQuickSettingsControllerTest {
@Test
fun `handleAutoplayAdd should store the updated permission and reload webpage`() =
coroutinesScope.runBlockingTest {
runTestOnMain {
val testPermissions = mockk<SitePermissions>()
controller.handleAutoplayAdd(testPermissions)
@ -305,7 +303,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleTrackingProtectionToggled should call the right use cases`() {
fun `handleTrackingProtectionToggled should call the right use cases`() = runTestOnMain {
val trackingProtectionUseCases: TrackingProtectionUseCases = mockk(relaxed = true)
val sessionUseCases: SessionUseCases = mockk(relaxed = true)
@ -338,7 +336,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `handleBlockedItemsClicked should call popBackStack and navigate to the tracking protection panel dialog`() {
fun `handleBlockedItemsClicked should call popBackStack and navigate to the tracking protection panel dialog`() = runTestOnMain {
every { context.components.core.store } returns browserStore
every { context.components.settings } returns appSettings
every { context.components.settings.toolbarPosition.androidGravity } returns mockk(relaxed = true)
@ -363,7 +361,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `WHEN handleConnectionDetailsClicked THEN call popBackStack and navigate to the connection details dialog`() {
fun `WHEN handleConnectionDetailsClicked THEN call popBackStack and navigate to the connection details dialog`() = runTestOnMain {
every { context.components.core.store } returns browserStore
every { context.components.settings } returns appSettings
every { context.components.settings.toolbarPosition.androidGravity } returns mockk(relaxed = true)
@ -387,7 +385,7 @@ class DefaultQuickSettingsControllerTest {
}
@Test
fun `WHEN handleClearSiteData THEN call clearSite`() {
fun `WHEN handleClearSiteData THEN call clearSite`() = runTestOnMain {
controller.handleClearSiteDataClicked("mozilla.org")
verify {
@ -411,7 +409,7 @@ class DefaultQuickSettingsControllerTest {
quickSettingsStore = store,
browserStore = browserStore,
sessionId = tab.id,
ioScope = coroutinesScope,
ioScope = scope,
navController = navController,
sitePermissions = sitePermissions,
settings = appSettings,

@ -4,7 +4,7 @@
package org.mozilla.fenix.settings.quicksettings
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.feature.sitepermissions.SitePermissionsRules
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@ -84,7 +84,7 @@ class QuickSettingsFragmentReducerTest {
}
@Test
fun `TrackingProtectionAction - ToggleTrackingProtectionEnabled`() = runBlocking {
fun `TrackingProtectionAction - ToggleTrackingProtectionEnabled`() = runTest {
val state = QuickSettingsFragmentState(
webInfoState = WebsiteInfoState("", "", WebsiteSecurityUiValues.SECURE, ""),
websitePermissionsState = emptyMap(),

@ -11,7 +11,7 @@ import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.state.BrowserState
import mozilla.components.browser.state.state.content.PermissionHighlightsState
import mozilla.components.browser.state.state.createTab
@ -234,7 +234,7 @@ class QuickSettingsFragmentStoreTest {
@Test
fun `TogglePermission should only modify status and visibility of a specific WebsitePermissionsState`() =
runBlocking {
runTest {
val initialCameraStatus = "initialCameraStatus"
val initialMicStatus = "initialMicStatus"
val initialNotificationStatus = "initialNotificationStatus"

@ -15,11 +15,10 @@ import io.mockk.mockk
import io.mockk.runs
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.test.TestCoroutineScope
import mozilla.components.service.nimbus.NimbusApi
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ -48,7 +47,7 @@ class StudiesViewTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testCoroutineScope = TestCoroutineScope(coroutinesTestRule.testDispatcher)
private val testCoroutineScope = coroutinesTestRule.scope
@Before
fun setup() {
@ -66,13 +65,8 @@ class StudiesViewTest {
)
}
@After
fun cleanUp() {
testCoroutineScope.cleanupTestCoroutines()
}
@Test
fun `WHEN calling bind THEN bind all the related information`() {
fun `WHEN calling bind THEN bind all the related information`() = runTestOnMain {
val studiesTitle = mockk<TextView>(relaxed = true)
val studiesSwitch = mockk<SwitchCompat>(relaxed = true)
val studiesList = mockk<RecyclerView>(relaxed = true)
@ -95,7 +89,7 @@ class StudiesViewTest {
}
@Test
fun `WHEN calling onRemoveButtonClicked THEN delegate to the interactor`() {
fun `WHEN calling onRemoveButtonClicked THEN delegate to the interactor`() = runTestOnMain {
val experiment = mockk<EnrolledExperiment>()
val adapter = mockk<StudiesAdapter>(relaxed = true)

@ -18,8 +18,7 @@ import io.mockk.slot
import io.mockk.spyk
import io.mockk.verify
import io.mockk.verifyOrder
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.advanceUntilIdle
import mozilla.components.concept.engine.prompt.ShareData
import mozilla.components.concept.sync.Device
import mozilla.components.concept.sync.DeviceType
@ -29,7 +28,7 @@ import mozilla.components.feature.share.RecentAppsStorage
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import org.junit.After
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
@ -72,17 +71,12 @@ class ShareControllerTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testDispatcher = coroutinesTestRule.testDispatcher
private val testCoroutineScope = TestCoroutineScope(testDispatcher)
private val testCoroutineScope = coroutinesTestRule.scope
private val controller = DefaultShareController(
context, shareSubject, shareData, sendTabUseCases, snackbar, navController,
recentAppStorage, testCoroutineScope, testDispatcher, dismiss
)
@After
fun cleanUp() {
testCoroutineScope.cleanupTestCoroutines()
}
@Test
fun `handleShareClosed should call a passed in delegate to close this`() {
controller.handleShareClosed()
@ -91,7 +85,7 @@ class ShareControllerTest {
}
@Test
fun `handleShareToApp should start a new sharing activity and close this`() = runBlocking {
fun `handleShareToApp should start a new sharing activity and close this`() = runTestOnMain {
val appPackageName = "package"
val appClassName = "activity"
val appShareOption = AppShareOption("app", mockk(), appPackageName, appClassName)
@ -108,7 +102,7 @@ class ShareControllerTest {
every { recentAppStorage.updateRecentApp(appShareOption.activityName) } just Runs
testController.handleShareToApp(appShareOption)
testDispatcher.advanceUntilIdle()
advanceUntilIdle()
// Check that the Intent used for querying apps has the expected structure
assertTrue(shareIntent.isCaptured)

@ -20,15 +20,15 @@ import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.feature.share.RecentApp
import mozilla.components.feature.share.RecentAppsStorage
import mozilla.components.service.fxa.manager.FxaAccountManager
import mozilla.components.support.test.robolectric.testContext
import org.junit.After
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.fenix.ext.application
@ -44,8 +44,11 @@ import org.robolectric.shadows.ShadowLooper
@RunWith(FenixRobolectricTestRunner::class)
class ShareViewModelTest {
@get:Rule
val coroutinesTestRule = MainCoroutineRule()
private val testIoDispatcher = coroutinesTestRule.testDispatcher
private val packageName = "org.mozilla.fenix"
private val testIoDispatcher = TestCoroutineDispatcher()
private lateinit var application: Application
private lateinit var packageManager: PackageManager
private lateinit var connectivityManager: ConnectivityManager
@ -75,11 +78,6 @@ class ShareViewModelTest {
)
}
@After
fun cleanUp() {
testIoDispatcher.cleanupTestCoroutines()
}
@Test
fun `liveData should be initialized as empty list`() {
assertEquals(emptyList<SyncShareOption>(), viewModel.devicesList.value)
@ -87,7 +85,7 @@ class ShareViewModelTest {
}
@Test
fun `loadDevicesAndApps`() = runBlockingTest {
fun `loadDevicesAndApps`() = runTestOnMain {
val appOptions = listOf(
AppShareOption("Label", mockk(), "Package", "Activity")
)
@ -164,7 +162,7 @@ class ShareViewModelTest {
}
@Test
fun `GIVEN only one app THEN show copy to clipboard before the app`() = runBlockingTest {
fun `GIVEN only one app THEN show copy to clipboard before the app`() = runTestOnMain {
val appOptions = listOf(
AppShareOption("Label", mockk(), "Package", "Activity")
)
@ -186,7 +184,7 @@ class ShareViewModelTest {
}
@Test
fun `WHEN no app THEN at least have copy to clipboard as app`() = runBlockingTest {
fun `WHEN no app THEN at least have copy to clipboard as app`() = runTestOnMain {
val appEntity = mockk<RecentApp>()
every { appEntity.activityName } returns "Activity"
every { storage.getRecentAppsUpTo(RECENT_APPS_LIMIT) } returns emptyList()

@ -14,7 +14,6 @@ import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkStatic
import io.mockk.verify
import kotlinx.coroutines.test.runBlockingTest
import mozilla.components.browser.state.selector.findTab
import mozilla.components.browser.state.selector.getNormalOrPrivateTabs
import mozilla.components.browser.state.state.BrowserState
@ -26,6 +25,7 @@ import mozilla.components.service.fxa.manager.FxaAccountManager
import mozilla.components.service.glean.testing.GleanTestRule
import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.rule.MainCoroutineRule
import mozilla.components.support.test.rule.runTestOnMain
import org.junit.Assert
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@ -203,7 +203,7 @@ class NavigationInteractorTest {
}
@Test
fun `onBookmarkTabs calls navigation on DefaultNavigationInteractor`() = runBlockingTest {
fun `onBookmarkTabs calls navigation on DefaultNavigationInteractor`() = runTestOnMain {
var showBookmarkSnackbarInvoked = false
createInteractor(
showBookmarkSnackbar = {

@ -5,7 +5,7 @@
package org.mozilla.fenix.trackingprotection
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import mozilla.components.browser.state.state.SessionState
import mozilla.components.concept.engine.content.blocking.TrackerLog
import org.junit.Assert.assertEquals
@ -17,7 +17,7 @@ class TrackingProtectionStoreTest {
val tab: SessionState = mockk(relaxed = true)
@Test
fun enterDetailsMode() = runBlocking {
fun enterDetailsMode() = runTest {
val initialState = defaultState()
val store = TrackingProtectionStore(initialState)
@ -37,7 +37,7 @@ class TrackingProtectionStoreTest {
}
@Test
fun exitDetailsMode() = runBlocking {
fun exitDetailsMode() = runTest {
val initialState = detailsState()
val store = TrackingProtectionStore(initialState)
@ -51,7 +51,7 @@ class TrackingProtectionStoreTest {
}
@Test
fun trackerListChanged() = runBlocking {
fun trackerListChanged() = runTest {
val initialState = defaultState()
val store = TrackingProtectionStore(initialState)
val tracker = TrackerLog("url", listOf())
@ -65,7 +65,7 @@ class TrackingProtectionStoreTest {
}
@Test
fun urlChanged() = runBlocking {
fun urlChanged() = runTest {
val initialState = defaultState()
val store = TrackingProtectionStore(initialState)
@ -78,7 +78,7 @@ class TrackingProtectionStoreTest {
}
@Test
fun onChange() = runBlocking {
fun onChange() = runTest {
val initialState = defaultState()
val store = TrackingProtectionStore(initialState)
val tracker = TrackerLog("url", listOf(), listOf(), cookiesHasBeenBlocked = false)

@ -4,7 +4,7 @@
package org.mozilla.fenix.wallpapers
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
@ -22,7 +22,7 @@ class WallpaperFileManagerTest {
private lateinit var landscapeLightFolder: File
private lateinit var landscapeDarkFolder: File
private val dispatcher = TestCoroutineDispatcher()
private val dispatcher = UnconfinedTestDispatcher()
private lateinit var fileManager: WallpaperFileManager

@ -7,7 +7,7 @@ import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@ -45,7 +45,7 @@ class WallpaperManagerTest {
}
@Test
fun `GIVEN no remote wallpapers expired and locale in promo WHEN downloading remote wallpapers THEN all downloaded`() = runBlockingTest {
fun `GIVEN no remote wallpapers expired and locale in promo WHEN downloading remote wallpapers THEN all downloaded`() = runTest {
every { mockSettings.currentWallpaper } returns ""
val fakeRemoteWallpapers = listOf("first", "second", "third").map { name ->
makeFakeRemoteWallpaper(TimeRelation.LATER, name)
@ -65,7 +65,7 @@ class WallpaperManagerTest {
}
@Test
fun `GIVEN no remote wallpapers expired and locale not in promo WHEN downloading remote wallpapers THEN none downloaded`() = runBlockingTest {
fun `GIVEN no remote wallpapers expired and locale not in promo WHEN downloading remote wallpapers THEN none downloaded`() = runTest {
every { mockSettings.currentWallpaper } returns ""
val fakeRemoteWallpapers = listOf("first", "second", "third").map { name ->
makeFakeRemoteWallpaper(TimeRelation.LATER, name)
@ -85,7 +85,7 @@ class WallpaperManagerTest {
}
@Test
fun `GIVEN no remote wallpapers expired and locale not in promo WHEN downloading remote wallpapers THEN non-promo wallpapers downloaded`() = runBlockingTest {
fun `GIVEN no remote wallpapers expired and locale not in promo WHEN downloading remote wallpapers THEN non-promo wallpapers downloaded`() = runTest {
every { mockSettings.currentWallpaper } returns ""
val fakePromoWallpapers = listOf("first", "second", "third").map { name ->
makeFakeRemoteWallpaper(TimeRelation.LATER, name)

@ -7,7 +7,7 @@
object Versions {
const val kotlin = "1.6.10"
const val coroutines = "1.5.2"
const val coroutines = "1.6.1"
// These versions are linked: lint should be X+23.Y.Z of gradle_plugin version, according to:
// https://github.com/alexjlockwood/android-lint-checks-demo/blob/0245fc027463137b1b4afb97c5295d60dce998b6/dependencies.gradle#L3

Loading…
Cancel
Save