Android multi module test dependency
Asked Answered
T

2

30

With Android Studio 3.0 / android_gradle_version = '3.0.1' / gradle-4.5

Let's say I have two android modules

module-base
module-a

When I want to access sources from module-base in module-a , I just need to write this in my module-a.gradle

dependencies {
    implementation project(path: ':module-base')
}

But, what if I want to access test sources from module-base in test of module-a? Here does not work approach like above

dependencies {
    testImplementation project(path: ':module-base')
}

I found lot of advices (few years old) which says something like

compileTestJava.dependsOn tasks.getByPath(':module-base:testClasses')
testCompile files(project(':module-base').sourceSets.test.output.classesDir)

or testCompile project(':module-base).sourceSets.test.classes

But no one from mentioned works. There is always something wrong from the compiler point of view :-/

Can you someone help me how to create Android test code dependency between two modules?

Tiana answered 22/3, 2018 at 19:5 Comment(3)
Did you find a solution? same problem for meCure
I have the same issue too ...Gmt
Workaround I have been using is here (look at module-test-utils) github.com/kotomisak/image-analyzer-androidTiana
S
11

In case anyone else ends up here, one way to accomplish this is to define the target module as a source set. Let's assume test-mdoule is the module we want to import stuff from, we can do it this way:

android {
    sourceSets {
        // non-instrumental test example
        test {
            java.srcDir project(":test-module").file("src/test/java")
        }
        // instrumental test example
        androidTest {
            java.srcDir project(":test-module").file("src/androidTest/java")
        }
    }
}

Reference: https://jonnycaley.medium.com/sharing-test-code-in-a-multi-module-android-project-7ce4de788016

Sisile answered 15/7, 2021 at 14:14 Comment(2)
This solution works fine with Gradle, but Android Studio Electric Eel still marks the shared code as Unresolved reference.Aldredge
Work fine in Electric EelIllogical
T
10

Actually I find just workaround for this. Don't use test sources from module-base but use sources from test related module module-testutils which is defined like this

dependencies{
   testImplementation project(':module-testutils')
}

Thus you can share common test code which will be excluded for non-testable apk.

Tiana answered 15/6, 2018 at 4:17 Comment(2)
What exactly is module-testutils? I mean, is it just another module created where you have your classes in src/main/java instead of src/test/java?Gmt
Yeah, for exact working code example I have been using just look at this android project: github.com/kotomisak/image-analyzer-androidTiana

© 2022 - 2024 — McMap. All rights reserved.