Skip to content

Commit 4167628

Browse files
authored
first (#831)
* single vs first * commit * commit * commit
1 parent 8a6032c commit 4167628

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.comparefirstandsingleUnitTests
2+
3+
import junit.framework.Assert.assertEquals
4+
import kotlinx.coroutines.flow.Flow
5+
import kotlinx.coroutines.flow.emptyFlow
6+
import kotlinx.coroutines.flow.first
7+
import kotlinx.coroutines.flow.flowOf
8+
import kotlinx.coroutines.runBlocking
9+
import org.junit.jupiter.api.Test
10+
import kotlin.test.assertFailsWith
11+
12+
13+
class FirstUnitTest {
14+
15+
@Test
16+
fun testFirstValue() = runBlocking {
17+
val multipleValuesFlow = flowOf(1, 2, 3)
18+
val firstValue = multipleValuesFlow.first()
19+
assertEquals(1, firstValue)
20+
}
21+
22+
@Test
23+
fun testFirstValueFromEmptyFlow() = runBlocking {
24+
val emptyFlow = emptyFlow<Int>()
25+
val exception = assertFailsWith<NoSuchElementException> {
26+
runBlocking {
27+
emptyFlow.first()
28+
}
29+
}
30+
assertEquals("Expected at least one element", exception.message)
31+
}
32+
33+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.comparefirstandsingleUnitTests
2+
3+
import junit.framework.Assert.assertEquals
4+
import kotlinx.coroutines.flow.flowOf
5+
import kotlinx.coroutines.flow.single
6+
import kotlinx.coroutines.runBlocking
7+
import org.junit.jupiter.api.Test
8+
import kotlin.test.assertFailsWith
9+
class SingleFunctionUnitTest {
10+
11+
@Test
12+
fun testSingleValue() = runBlocking {
13+
val multipleValuesFlow = flowOf(42)
14+
val singleValue = multipleValuesFlow.single()
15+
assertEquals(42, singleValue)
16+
}
17+
18+
@Test
19+
fun testExceptionForMultipleValues() = runBlocking {
20+
val multipleValues = flowOf(42, 43, 44)
21+
val exception = assertFailsWith<IllegalArgumentException> {
22+
runBlocking {
23+
multipleValues.single()
24+
}
25+
}
26+
assertEquals("Flow has more than one element", exception.message)
27+
}
28+
29+
@Test
30+
fun testIllegalArgumentException() = runBlocking {
31+
val emptyFlow = flowOf<Int>()
32+
val exception = assertFailsWith<NoSuchElementException> {
33+
runBlocking {
34+
emptyFlow.single()
35+
}
36+
}
37+
assertEquals("Flow is empty", exception.message)
38+
}
39+
}

0 commit comments

Comments
 (0)