Skip to content

Commit 6fba929

Browse files
naoussinappy29
andauthored
[KTLN-491] Destructor in Kotlin Programming Language (#1057)
* added unit tests * added unit tests * added unit tests --------- Co-authored-by: nappy29 <[email protected]>
1 parent 33b564b commit 6fba929

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.baeldung.destructorsInKotlin
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
import org.mockito.Mockito.*
6+
import java.io.BufferedReader
7+
import java.io.IOException
8+
import kotlin.test.assertFailsWith
9+
10+
class DestructorsInKotlinUnitTest {
11+
@Test
12+
@Throws(IOException::class)
13+
fun `perform resource cleaning with try-finally block`() {
14+
val mockReader = mock(BufferedReader::class.java)
15+
`when`(mockReader.readLine()).thenReturn("Hello, Kotlin!", null)
16+
17+
val content = readFile(mockReader)
18+
assertEquals("Hello, Kotlin!", content)
19+
20+
verify(mockReader).close()
21+
}
22+
23+
@Test
24+
@Throws(IOException::class)
25+
fun `perform resource cleaning with try-finally block when IOException occurs`() {
26+
val mockReader = mock(BufferedReader::class.java)
27+
`when`(mockReader.readLine()).thenThrow(IOException("Test exception"))
28+
29+
assertFailsWith<IOException> {
30+
readFile(mockReader)
31+
}
32+
33+
verify(mockReader).close()
34+
}
35+
36+
@Test
37+
@Throws(IOException::class)
38+
fun `perform resource cleaning with use`() {
39+
val mockReader = mock(BufferedReader::class.java)
40+
`when`(mockReader.readLine()).thenReturn("Hello, Kotlin!", null)
41+
val content = readFileUsingUse(mockReader)
42+
assertEquals("Hello, Kotlin!", content)
43+
44+
verify(mockReader).close()
45+
}
46+
47+
@Test
48+
@Throws(IOException::class)
49+
fun `perform resource cleaning with use() when IOException occurs`() {
50+
val mockReader = mock(BufferedReader::class.java)
51+
`when`(mockReader.readLine()).thenThrow(IOException("Test exception"))
52+
53+
assertFailsWith<IOException> {
54+
readFileUsingUse(mockReader)
55+
}
56+
57+
verify(mockReader).close()
58+
}
59+
}
60+
61+
@Throws(IOException::class)
62+
fun readFile(reader: BufferedReader): String {
63+
try {
64+
val content = StringBuilder()
65+
var line: String?
66+
while ((reader.readLine().also { line = it }) != null) {
67+
content.append(line)
68+
}
69+
return content.toString()
70+
} finally {
71+
reader.close()
72+
}
73+
}
74+
75+
@Throws(IOException::class)
76+
fun readFileUsingUse(reader: BufferedReader): String {
77+
return reader.use { br ->
78+
val content = StringBuilder()
79+
var line: String?
80+
while ((br.readLine().also { line = it }) != null) {
81+
content.append(line)
82+
}
83+
content.toString()
84+
}
85+
}

0 commit comments

Comments
 (0)