/
CastToNullableTypeSpec.kt
55 lines (49 loc) · 1.52 KB
/
CastToNullableTypeSpec.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.junit.jupiter.api.Test
class CastToNullableTypeSpec {
private val subject = CastToNullableType()
@Test
fun `casting to nullable types`() {
val code = """
fun foo(a: Any?) {
val x: String? = a as String?
}
""".trimIndent()
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasStartSourceLocation(2, 24)
assertThat(findings[0]).hasMessage("Use the safe cast ('as? String') instead of 'as String?'.")
}
@Test
fun `safe casting`() {
val code = """
fun foo(a: Any?) {
val x: String? = a as? String
}
""".trimIndent()
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
@Test
fun `type checking`() {
val code = """
fun foo(a: Any?) {
val x = a is String?
}
""".trimIndent()
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
@Test
fun `cast null to nullable type is allowed`() {
val code = """
fun foo(a: Any?) {
val x = null as String?
}
""".trimIndent()
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}