Skip to content

Commit 7068f05

Browse files
authored
[rm-last-element] Remove the Last Element in a List in Kotlin (#657)
1 parent 51ebfee commit 7068f05

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.baeldung.removeTheLastElement
2+
3+
import org.junit.jupiter.api.Test
4+
import org.junit.jupiter.api.assertThrows
5+
import kotlin.test.assertEquals
6+
import kotlin.test.assertTrue
7+
8+
class RemoveTheLastElementUnitTest {
9+
@Test
10+
fun `when calling removeLast() on mutableList then get the expected result`() {
11+
val mutableList = mutableListOf("a", "b", "c", "d", "e")
12+
mutableList.removeLast()
13+
assertEquals(listOf("a", "b", "c", "d"), mutableList)
14+
15+
assertThrows<NoSuchElementException> {
16+
mutableListOf<String>().removeLast()
17+
}
18+
}
19+
20+
@Test
21+
fun `when calling removeAt() on mutableList then get the expected result`() {
22+
val mutableList = mutableListOf("a", "b", "c", "d", "e")
23+
mutableList.removeAt(mutableList.lastIndex)
24+
assertEquals(listOf("a", "b", "c", "d"), mutableList)
25+
26+
val emptyMutableList = mutableListOf<String>()
27+
assertThrows<IndexOutOfBoundsException> {
28+
emptyMutableList.removeAt(emptyMutableList.lastIndex)
29+
}.also {
30+
assertEquals("Index -1 out of bounds for length 0", it.message)
31+
}
32+
}
33+
34+
@Test
35+
fun `when calling subList() on read-only list then get the expected result`() {
36+
val myList = listOf("a", "b", "c", "d", "e")
37+
val result = myList.subList(0, myList.lastIndex)
38+
assertEquals(listOf("a", "b", "c", "d"), result)
39+
40+
val myEmptyList = emptyList<String>()
41+
assertThrows<IndexOutOfBoundsException> {
42+
myEmptyList.subList(0, myEmptyList.lastIndex)
43+
}.also {
44+
assertEquals("fromIndex: 0, toIndex: -1", it.message)
45+
}
46+
}
47+
48+
@Test
49+
fun `when calling droplast() on read-only list then get the expected result`() {
50+
val myList = listOf("a", "b", "c", "d", "e")
51+
val result = myList.dropLast(1)
52+
assertEquals(listOf("a", "b", "c", "d"), result)
53+
54+
val myEmptyList = emptyList<String>()
55+
assertTrue { myEmptyList.dropLast(1).isEmpty() }
56+
}
57+
}

0 commit comments

Comments
 (0)