Skip to content

Commit 2709147

Browse files
committed
refactor: Simplify reflection logic in ComposeTestNodeProvider
- The `reflect` function has been refactored to simplify the process of accessing the internal `ComposeUiTest` from a `ComposeContentTestRule`. - Removed the separate `findField` and `getOrNull` helper functions. - The reflection logic is now consolidated directly within the `reflect` function, using a `try-catch` block to handle potential `NoSuchFieldException` and `IllegalAccessException`.
1 parent 3b5cac0 commit 2709147

File tree

1 file changed

+10
-24
lines changed

1 file changed

+10
-24
lines changed

ui/test-jvm/src/main/kotlin/com/softartdev/notedelight/ComposeTestNodeProvider.kt

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,33 +5,19 @@ package com.softartdev.notedelight
55
import androidx.compose.ui.test.ComposeUiTest
66
import androidx.compose.ui.test.ExperimentalTestApi
77
import androidx.compose.ui.test.junit4.ComposeContentTestRule
8-
import java.lang.reflect.Field
98

109
fun reflect(composeTestRule: ComposeContentTestRule): ComposeUiTest {
11-
findField(composeTestRule, "composeTest")?.let { field ->
12-
field.getOrNull(composeTestRule)?.let { value ->
13-
if (value is ComposeUiTest) return value
14-
}
15-
}
16-
throw IllegalStateException(
17-
"Failed to reflect ComposeUiTest from ${composeTestRule.javaClass.name}. " +
18-
"Expected AndroidComposeTestRule/DesktopComposeTestRule internals to contain it."
19-
)
20-
}
21-
22-
@Suppress("SameParameterValue")
23-
private fun findField(target: Any, name: String): Field? {
24-
var c: Class<*>? = target.javaClass
10+
var c: Class<*>? = composeTestRule.javaClass
2511
while (c != null && c != Any::class.java) {
26-
runCatching { c.getDeclaredField(name) }
27-
.onSuccess { return it }
12+
try {
13+
val f = c.getDeclaredField("composeTest")
14+
f.isAccessible = true
15+
val v = f.get(composeTestRule)
16+
if (v is ComposeUiTest) return v
17+
} catch (_: NoSuchFieldException) {
18+
} catch (_: IllegalAccessException) {
19+
}
2820
c = c.superclass
2921
}
30-
return null
22+
throw IllegalStateException("ComposeUiTest not found")
3123
}
32-
33-
private fun Field.getOrNull(instance: Any): Any? =
34-
runCatching {
35-
isAccessible = true
36-
get(instance)
37-
}.getOrNull()

0 commit comments

Comments
 (0)