Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lessons From Writing a Custom Testing Framework...

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

Lessons From Writing a Custom Testing Framework - Droidcon India 2026

Subhrajyoti Sen

November 20, 2026

Transcript

101 slides
  1. Lessons From Writing a Custom Testing Framework Subhrajyoti Sen Senior

    Software Engineer @ Adyen GDE for Android @iamsubhrajyoti
  2. The Complexity • Multiple engines - Android Instrumentation, Appium •

    Multiple targets - Emulators, Physical Devices, Robots • Multiple apps • Multiple OEMs • Devices without ADB • Complex Filtering
  3. internal class DelegatingTestRunner( private val testClass: Class<*> ) : Runner()

    { private val strategy: RunnerStrategy by lazy { //.. } override fun getDescription(): Description = strategy.getDescription() override fun run(notifier: RunNotifier) { strategy.run(notifier) } }
  4. interface RunnerStrategy : Filterable { val name: String val tag:

    String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() }
  5. private val strategy: RunnerStrategy by lazy { val runnerType =

    System.getProperty("test.runner.type") val loader = ServiceLoader.load(RunnerStrategy::class.java) val foundStrategy = loader.find { it.name == runnerType } ?: error("Could not find a RunnerStrategy with name '$runnerType'") foundStrategy.init(testClass) foundStrategy }
  6. private val strategy: RunnerStrategy by lazy { val runnerType =

    System.getProperty("test.runner.type") val loader = ServiceLoader.load(RunnerStrategy::class.java) val foundStrategy = loader.find { it.name == runnerType } ?: error("Could not find a RunnerStrategy with name '$runnerType'") foundStrategy.init(testClass) foundStrategy }
  7. private val strategy: RunnerStrategy by lazy { val runnerType =

    System.getProperty("test.runner.type") val loader = ServiceLoader.load(RunnerStrategy::class.java) val foundStrategy = loader.find { it.name == runnerType } ?: error("Could not find a RunnerStrategy with name '$runnerType'") foundStrategy.init(testClass) foundStrategy }
  8. private val strategy: RunnerStrategy by lazy { val runnerType =

    System.getProperty("test.runner.type") val loader = ServiceLoader.load(RunnerStrategy::class.java) val foundStrategy = loader.find { it.name == runnerType } ?: error("Could not find a RunnerStrategy with name '$runnerType'") foundStrategy.init(testClass) foundStrategy }
  9. class AITRunnerStrategy : RunnerStrategy { override val name = "instrumented"

    override val tag = "AITStrategy" private lateinit var delegateRunner: AITClassRunner } class AITClassRunner( testClass: Class<*>, private val testInstance: Any ) : AndroidJUnit4ClassRunner(testClass)
  10. class AppiumRunnerStrategy : RunnerStrategy { override val name = "appium"

    override val tag = "AppiumRunnerStrategy" private lateinit var delegateRunner: AppiumClassRunner } class AppiumClassRunner( testClass: Class<*>, private val testInstance: Any ) : BlockJUnit4ClassRunner(testClass)
  11. @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {} @AccountConfig(STORE1) @Test

    fun test2() {} @Test fun test3() {} @AccountConfig(STORE1) @Test fun test4() {} }
  12. Boarding • Assign a device to a new account •

    Wait for the backend to apply changes • Wait for the device to be notified via the backend • Wait for the device to download and configure required files
  13. internal class AccountConfigComparator : Comparator<Description> { override fun compare( d1:

    Description, d2: Description ): Int { //.. } @Suppress("UNCHECKED_CAST") private fun compareConfigs( c1: AccountConfiguration, c2: AccountConfiguration ): Int { return (c1 as Comparable<Any>).compareTo(c2) } }
  14. internal class AccountConfigComparator : Comparator<Description> { override fun compare( d1:

    Description, d2: Description ): Int { val config1 = getAccountConfig(d1) val config2 = getAccountConfig(d2) return when { config1 == null && config2 == null -> 0 config1 == null -> 1 config2 == null -> -1 else -> compareConfigs(config1, config2) } } }
  15. interface RunnerStrategy : Filterable { val name: String val tag:

    String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() }
  16. interface RunnerStrategy : Filterable, Sortable { val name: String val

    tag: String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() }
  17. internal class DelegatingTestRunner(private val testClass: Class<*>) : Runner(), Filterable {

    private val strategy: RunnerStrategy by lazy { //.. val foundStrategy = loader.find { it.name == runnerType } ?: error("Could not find a RunnerStrategy with name '$runnerType'") val accountSorter = Sorter(AccountConfigComparator()) foundStrategy.sort(accountSorter) foundStrategy }
  18. @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {} @AccountConfig(STORE1) @Test

    fun test2() {} } @AccountConfig(STORE1) class TestClass2 { @AccountConfig(REFUND_STORE) @Test fun test3() {} @Test fun test4() {} }
  19. @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {} @AccountConfig(STORE1) @Test

    fun test2() {} } @AccountConfig(STORE1) class TestClass2 { @AccountConfig(REFUND_STORE) @Test fun test3() {} @Test fun test4() {} }
  20. @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {} @AccountConfig(STORE1) @Test

    fun test2() {} } @AccountConfig(STORE1) class TestClass2 { @AccountConfig(REFUND_STORE) @Test fun test3() {} @Test fun test4() {} }
  21. Kotlin Symbol Processing(KSP) • A special type of Kotlin Compiler

    Plugin • It can only generate new code • Stable APIs • It can access only symbols and declarations; no expressions
  22. Source Code @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {

    Shopper.PresentCard(CardImage.VISA_4321) Verify.Screen(Screen.FINAL) } }
  23. What KSP Sees @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1()

    { Shopper.PresentCard(CardImage.VISA_4321) Verify.Screen(Screen.FINAL) } }
  24. KSP Representation (Summarized) KSFile ("TestClass1.kt") └── KSClassDeclaration ("TestClass1") ├── KSAnnotation

    ("@AccountConfig") │ └── KSValueArgument (value = REFUND_STORE) └── KSFunctionDeclaration ("test1") ├── KSAnnotation ("@Test") ├── parameters: [] └── returnType: Unit
  25. KSP Processor class AccountConfigProcessor( val codeGenerator: CodeGenerator ) : SymbolProcessor

    { override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver .getSymbolsWithAnnotation(ACCOUNT_CONFIG.canonicalName) .toList() //.. } }
  26. KSP Processor class AccountConfigProcessor( val codeGenerator: CodeGenerator ) : SymbolProcessor

    { override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver .getSymbolsWithAnnotation(ACCOUNT_CONFIG.canonicalName) .toList() //.. } }
  27. KSP Processor val accountConfigs = getAllAccountConfigs() val accountConfigMap = parseSymbols(

    symbols, accountConfigs, resolver ) generatedAccountConfigClaases( accountConfigMap, generator )
  28. KSP Processor fun generatedAccountConfigClaases( accountConfigMap: Map<AccountConfiguration, List<KSAnnotated>, codeGenerator: CodeGenerator )

    { accountConfigMap.forEach {config, symbols -> val fileSpecBuilder = //.. fileSpecBuilder .build() .writeTo( codeGenerator = codeGenerator, aggregating = true, originatingKSFiles = resolver.getAllFiles().toList(), ) }
  29. Isolating Mode val dependencies = Dependencies( aggregating = false, listOf("ParkingEntity")

    ) val os = codeGenerator.createNewFile( dependencies = dependencies, packageName = "com.example.generated", fileName = "ParkingRepository" )
  30. Aggregating Mode val dependencies = Dependencies( aggregating = true, listOf("StartupWorker1",

    "StartupWorker2) ) val os = codeGenerator.createNewFile( dependencies = dependencies, packageName = "com.example.generated", fileName = "StartupRegistry" )
  31. @Test fun happyFlowCtls() = runUtfTest { Merchant.SendNexo( getGenericPaymentRequest( BigDecimal.valueOf(11), "EUR"

    ) ) Verify.Screen.Displayed(TerminalScreen.PresentCard) Shopper.PresentCard(CardImage.AMEX) Verify.Screen.Displayed(TerminalScreen.FINAL_RESULT) }
  32. @Test fun happyFlowCtls() = runUtfTest { Merchant.SendNexo( getGenericPaymentRequest( BigDecimal.valueOf(11), "EUR"

    ) ) Verify.Screen.Displayed(TerminalScreen.PresentCard) Shopper.PresentCard(CardImage.AMEX) Verify.Screen.Displayed(TerminalScreen.FINAL_RESULT) }
  33. @Test @CTLS fun happyFlowCtls() = runUtfTest { Merchant.SendNexo( getGenericPaymentRequest( BigDecimal.valueOf(11),

    "EUR" ) ) Verify.Screen.Displayed(TerminalScreen.PresentCard) Shopper.PresentCard(CardImage.AMEX) Verify.Screen.Displayed(TerminalScreen.FINAL_RESULT) }
  34. Kotlin Compiler Plugins • It can generate new code •

    It can edit existing code • Unstable APIs • It can access expressions
  35. FIR Plugin • FIR - Frontend Intermediate Representation • Parses

    .kt files, resolves symbols, infers types • Changes are visible in the IDE • Can be used to: ◦ Enforce custom language rules ◦ Modify modifiers and supertypes ◦ Add stubs
  36. IR Plugin • Backend plugin • Changes aren’t visible in

    the IDE • Can be used to : ◦ Implement stubbed bodies ◦ Rewrite Expressions
  37. @Test @CTLS fun happyFlowCtls() = runUtfTest { Merchant.SendNexo( getGenericPaymentRequest( BigDecimal.valueOf(11),

    "EUR" ) ) Verify.Screen.Displayed(TerminalScreen.PresentCard) Shopper.PresentCard(CardImage.AMEX) Verify.Screen.Displayed(TerminalScreen.FINAL_RESULT) }
  38. @Test @CTLS <- IR Plugin fun happyFlowCtls() = runUtfTest {

    Merchant.SendNexo( getGenericPaymentRequest( BigDecimal.valueOf(11), "EUR" ) ) Verify.Screen.Displayed(TerminalScreen.PresentCard) Shopper.PresentCard(CardImage.AMEX) Verify.Screen.Displayed(TerminalScreen.FINAL_RESULT) }
  39. private fun getMethodRunners(suiteClass: Class<*>): List<Runner> { val selectMethods = suiteClass

    .getAnnotation(SelectMethods::class.java) ?: return emptyList() val runners = mutableListOf<Runner>() for (selection in selectMethods.value) { //.. } return runners }
  40. for (selection in selectMethods.value) { val testClass = selection.testClass.java val

    methodName = selection.methodName val testDescription = Description.createTestDescription(testClass, methodName) val request = Request.aClass(testClass).filterWith(testDescription) runners.add(request.runner) }
  41. ADB In A Gradle Task abstract class AllureResultRetrievalTask : DefaultTask()

    { @TaskAction fun taskAction() { val resultsDir = dir("allure-results").get().asFile.absolutePath pullResults(resultsDir) } }
  42. ADB In A Gradle Task private fun pullResults(localPath: String) {

    execOperations.exec { executable = "adb" args = listOf("pull", localResultPath, localPath) errorOutput = System.err isIgnoreExitValue = true } }
  43. Fetching ADB Path at Runtime private fun pullResults(localPath: String) {

    execOperations.exec { executable = "adb" args = listOf("pull", localResultPath, localPath) errorOutput = System.err isIgnoreExitValue = true } }
  44. Easy Fix - Fetch ADB From SDK Components @TaskAction fun

    taskAction() { val androidComponents = project.extensions.findByType(AndroidComponentsExtension::class.java) val adbPath = androidComponents.sdkComponents.adb.get().asFile.absolutePath val resultsDir = //.. pullResults(adbPath, resultsDir) }
  45. Gradle Configuration Cache ./gradlew allurePullResult > Task allurePullResult FAILED 2

    problems were found storing the configuration cache. - Task `allurePullResult` of type `AllureResultRetrievalTask`: invocation of 'Task.project' at execution time is unsupported with the configuration cache.
  46. Better Fix abstract class AllureResultRetrievalTask : DefaultTask() { @get:Optional @get:InputFile

    @get:PathSensitive(PathSensitivity.NONE) abstract val adbExecutable: RegularFileProperty @TaskAction fun taskAction() { val resultsDir = layout.buildDirectory.dir("allure-results").get().asFile.absolutePath val adbPath = adbExecutable.get().asFile.absolutePath pullResults(resultsDir) } }
  47. Better Fix abstract class AllureResultRetrievalTask : DefaultTask() { @get:Optional @get:InputFile

    @get:PathSensitive(PathSensitivity.NONE) abstract val adbExecutable: RegularFileProperty @TaskAction fun taskAction() { val resultsDir = layout.buildDirectory.dir("allure-results").get().asFile.absolutePath val adbPath = adbExecutable.get().asFile.absolutePath pullResults(resultsDir) } }
  48. Better Fix abstract class AllureResultRetrievalTask : DefaultTask() { @get:Optional @get:InputFile

    @get:PathSensitive(PathSensitivity.NONE) abstract val adbExecutable: RegularFileProperty @TaskAction fun taskAction() { val resultsDir = layout.buildDirectory.dir("allure-results").get().asFile.absolutePath val adbPath = adbExecutable.get().asFile.absolutePath pullResults(resultsDir) } }
  49. class AllureReportPlugin : Plugin<Project> { override fun apply(target: Project) {

    val pullTask = target.tasks.register(RESULT_TASK_NAME, AllureResultTask::class.java) listOf("com.android.application", "com.android.library").forEach { id -> target.pluginManager.withPlugin(id) { val adb = target .extensions .getByType(AndroidComponentsExtension::class.java) .sdkComponents .adb pullTask.configure { adbExecutable.set(adb) } } } }
  50. Line Marker Provider class UtfLineMarkerProvider : LineMarkerProviderDescriptor() { override fun

    getName(): String = "UTF test runner (AIT / Appium)" override fun getIcon(): Icon = UtfIcons.RUN override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { //.. } }
  51. Line Marker Provider override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { //..

    return LineMarkerInfo( element, element.textRange, UtfIcons.RUN, { "Run UTF test '${target.displayName}' on AIT or Appium" }, { event, psi -> showRunnerPopup(event, psi, target) }, GutterIconRenderer.Alignment.LEFT, { "Run UTF test ${target.displayName}" }, ) }
  52. Line Marker Provider override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { //..

    return LineMarkerInfo( element, element.textRange, UtfIcons.RUN, { "Run UTF test '${target.displayName}' on AIT or Appium" }, { event, psi -> showRunnerPopup(event, psi, target) }, GutterIconRenderer.Alignment.LEFT, { "Run UTF test ${target.displayName}" }, ) }
  53. Line Marker Provider private fun showRunnerPopup( event: MouseEvent, element: PsiElement,

    target: UtfTestTarget ) { //.. JBPopupFactory.getInstance() .createActionGroupPopup( target.displayName, group, DataManager.getInstance().getDataContext(event.component), JBPopupFactory.ActionSelectionAid.NUMBERING, true, ) .show(RelativePoint(event)) }
  54. runIde Configuration val androidStudioPath = providers.gradleProperty("androidStudioPath").get() dependencies { intellijPlatform {

    local(androidStudioPath) bundledPlugin("com.intellij.java") bundledPlugin("org.jetbrains.kotlin") bundledPlugin("com.intellij.gradle") } }
  55. runIde Configuration ./gradlew runIde -PandroidStudioPath=/Applications/JetBrains/IDES/Android\ Studio.app • • • •

    Complies the plugin Packages the plugin into a JAR Copies the JAR into the sandbox’s plugin system Launches Android Studio with a custom config, system, logs and plugins
  56. Lessons • JUnit is super extensible - extend anything and

    proceed • KSP for when you need to only generate code • Compiler Plugins for when you need to edit existing code • IDE Plugins for better DX • Care about Gradle Configuration Cache • With enough effort, a lot of “new features” can be backported

More Decks by Subhrajyoti Sen

Other Decks in Programming