Share
Embed
Lessons From Writing a Custom Testing Framework - Droidcon India 2026
Subhrajyoti Sen
November 20, 2026
Transcript
101 slides
-
Lessons From Writing a Custom Testing Framework Subhrajyoti Sen Senior
Software Engineer @ Adyen GDE for Android @iamsubhrajyoti -
The Complexity • Multiple engines - Android Instrumentation, Appium •
Multiple targets - Emulators, Physical Devices, Robots • Multiple apps • Multiple OEMs • Devices without ADB • Complex Filtering -
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) } } -
interface RunnerStrategy : Filterable { val name: String val tag:
String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() } -
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 } -
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 } -
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 } -
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 } -
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) -
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) -
@AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {} @AccountConfig(STORE1) @Test
fun test2() {} @Test fun test3() {} @AccountConfig(STORE1) @Test fun test4() {} } -
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 -
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) } } -
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) } } } -
interface RunnerStrategy : Filterable { val name: String val tag:
String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() } -
interface RunnerStrategy : Filterable, Sortable { val name: String val
tag: String fun init(testClass: Class<*>) fun run(notifier: RunNotifier) fun getDescription(): Description fun setupTestDependencies() } -
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 } -
@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() {} } -
@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() {} } -
@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() {} } -
@Suite @Suite @SelectMethods( @SelectMethods( SelectMethod("TestClass1#test1") SelectMethod("TestClass1#test2") SelectMethod("TestClass2#test4") SelectMethod("TestClass2#test3") ) )
public class REFUND_STORE_TestSuite public class STORE1_TestSuite -
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 -
Source Code @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1() {
Shopper.PresentCard(CardImage.VISA_4321) Verify.Screen(Screen.FINAL) } } -
What KSP Sees @AccountConfig(REFUND_STORE) class TestClass1 { @Test fun test1()
{ Shopper.PresentCard(CardImage.VISA_4321) Verify.Screen(Screen.FINAL) } } -
KSP Representation (Summarized) KSFile ("TestClass1.kt") └── KSClassDeclaration ("TestClass1") ├── KSAnnotation
("@AccountConfig") │ └── KSValueArgument (value = REFUND_STORE) └── KSFunctionDeclaration ("test1") ├── KSAnnotation ("@Test") ├── parameters: [] └── returnType: Unit -
KSP Processor class AccountConfigProcessor( val codeGenerator: CodeGenerator ) : SymbolProcessor
{ override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver .getSymbolsWithAnnotation(ACCOUNT_CONFIG.canonicalName) .toList() //.. } } -
KSP Processor class AccountConfigProcessor( val codeGenerator: CodeGenerator ) : SymbolProcessor
{ override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver .getSymbolsWithAnnotation(ACCOUNT_CONFIG.canonicalName) .toList() //.. } } -
KSP Processor val accountConfigs = getAllAccountConfigs() val accountConfigMap = parseSymbols(
symbols, accountConfigs, resolver ) generatedAccountConfigClaases( accountConfigMap, generator ) -
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(), ) } -
KSP Processor .writeTo( codeGenerator = codeGenerator, aggregating = true, originatingKSFiles
= resolver.getAllFiles().toList(), ) -
Incremental Annotation Processing - KSP KSP supports 2 output types:
1. Aggregating 2. Isolating -
Isolating 1-1 or many-1 relationship Example: Generating a `<Type>Repository` for
each class annotated with `@Entity` -
Aggregating Many-1 relationship Example: Generating a `StartupRegistry` class for each
class annotated with `@Startup` -
Isolating Mode val dependencies = Dependencies( aggregating = false, listOf("ParkingEntity")
) val os = codeGenerator.createNewFile( dependencies = dependencies, packageName = "com.example.generated", fileName = "ParkingRepository" ) -
Aggregating Mode val dependencies = Dependencies( aggregating = true, listOf("StartupWorker1",
"StartupWorker2) ) val os = codeGenerator.createNewFile( dependencies = dependencies, packageName = "com.example.generated", fileName = "StartupRegistry" ) -
@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) } -
@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) } -
@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) } -
Kotlin Compiler Plugins • It can generate new code •
It can edit existing code • Unstable APIs • It can access expressions -
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 -
IR Plugin • Backend plugin • Changes aren’t visible in
the IDE • Can be used to : ◦ Implement stubbed bodies ◦ Rewrite Expressions -
@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) } -
@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) } -
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 } -
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) } -
ADB In A Gradle Task abstract class AllureResultRetrievalTask : DefaultTask()
{ @TaskAction fun taskAction() { val resultsDir = dir("allure-results").get().asFile.absolutePath pullResults(resultsDir) } } -
ADB In A Gradle Task private fun pullResults(localPath: String) {
execOperations.exec { executable = "adb" args = listOf("pull", localResultPath, localPath) errorOutput = System.err isIgnoreExitValue = true } } -
Fetching ADB Path at Runtime private fun pullResults(localPath: String) {
execOperations.exec { executable = "adb" args = listOf("pull", localResultPath, localPath) errorOutput = System.err isIgnoreExitValue = true } } -
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) } -
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. -
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) } } -
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) } } -
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) } } -
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) } } } } -
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<*>? { //.. } } -
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}" }, ) } -
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}" }, ) } -
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)) } -
runIde Configuration val androidStudioPath = providers.gradleProperty("androidStudioPath").get() dependencies { intellijPlatform {
local(androidStudioPath) bundledPlugin("com.intellij.java") bundledPlugin("org.jetbrains.kotlin") bundledPlugin("com.intellij.gradle") } } -
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 -
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