|
| 1 | +package org.ole.planet.myplanet.services |
| 2 | + |
| 3 | +import android.content.Intent |
| 4 | +import kotlinx.coroutines.ExperimentalCoroutinesApi |
| 5 | +import kotlinx.coroutines.flow.first |
| 6 | +import kotlinx.coroutines.launch |
| 7 | +import kotlinx.coroutines.test.UnconfinedTestDispatcher |
| 8 | +import kotlinx.coroutines.test.runTest |
| 9 | +import org.junit.Assert.assertEquals |
| 10 | +import org.junit.Assert.assertTrue |
| 11 | +import org.junit.Before |
| 12 | +import org.junit.Test |
| 13 | + |
| 14 | +@OptIn(ExperimentalCoroutinesApi::class) |
| 15 | +class BroadcastServiceTest { |
| 16 | + |
| 17 | + private lateinit var broadcastService: BroadcastService |
| 18 | + |
| 19 | + @Before |
| 20 | + fun setUp() { |
| 21 | + broadcastService = BroadcastService() |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + fun `sendBroadcast emits intent`() = runTest { |
| 26 | + val testIntent = Intent("TEST_ACTION") |
| 27 | + var receivedIntent: Intent? = null |
| 28 | + |
| 29 | + val job = launch(UnconfinedTestDispatcher(testScheduler)) { |
| 30 | + receivedIntent = broadcastService.events.first() |
| 31 | + } |
| 32 | + |
| 33 | + broadcastService.sendBroadcast(testIntent) |
| 34 | + |
| 35 | + job.join() |
| 36 | + assertEquals(testIntent, receivedIntent) |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + fun `trySendBroadcast emits intent and returns true`() = runTest { |
| 41 | + val testIntent = Intent("TEST_ACTION") |
| 42 | + var receivedIntent: Intent? = null |
| 43 | + |
| 44 | + val job = launch(UnconfinedTestDispatcher(testScheduler)) { |
| 45 | + receivedIntent = broadcastService.events.first() |
| 46 | + } |
| 47 | + |
| 48 | + val result = broadcastService.trySendBroadcast(testIntent) |
| 49 | + |
| 50 | + job.join() |
| 51 | + assertTrue(result) |
| 52 | + assertEquals(testIntent, receivedIntent) |
| 53 | + } |
| 54 | +} |
0 commit comments