27

I have android app project, working in Android Studio. My application files are in the my.package package My unit tests are in my.package.unittest package And my espresso tests are in my.package.androidtest package

In one of my espresso tests I need to use one class that I have under the unittest package, but I am not able to.

Unittest class, that I need to use is located in app/src/test/java folder:

package my.package.unittest;
public class HelperClass {
...
}

And the file I am trying to use it in is in app/src/androidTest/java folder:

package my.package.androidtest;

import static my.package.unittest.*;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class AppTest {
    HelperClass.staticMethod();
}

The error I get is: cannot resolve symbol HelperClass

Additional info:

import my.package.unittest.HelperClass;

This itself gives "cannot resolve symbol" error.

What is the correct way to use this HelperClass from my UnitTests in my Espresso tests.

4

1 Answer 1

44

The correct answer was pointed by @Jeremy Kao.

1 -> Create a directory inside app/src. You can call it testShared.

2 -> Put your classes inside this directory.

3 -> inside app/build.gradle put:

android.sourceSets {  
    test {
        java.srcDirs += "$projectDir/src/testShared"
    }

    androidTest {
        java.srcDirs += "$projectDir/src/testShared"
    }
}

Put this anywhere outside the android closure.

4 -> Have fun!

Resources:

http://trickyandroid.com/android-test-tricks-sharing-code-between-unit-ui-tests/

7
  • Instead of java.srcDirs I did main.java.srcDirs, otherwise it wasn't working.
    – azizbekian
    Feb 7, 2020 at 11:13
  • 5
    Both java.srcDirs and main.java.srcDirs worked for me. Also, the closure does not need to be put outside of the android closure. It can be put inside it, but you just need to change android.sourceSets to just sourceSets Apr 17, 2020 at 22:16
  • 1
    indeed, your observation is very correct @MartinMelka. Thanks! Apr 20, 2020 at 16:59
  • any idea how to prevent Android Studio from removing the "mark as test sources" marker? really annoying to re-mark after a gradle sync.. Aug 18, 2021 at 9:51
  • 1
    This no longer works as of AndroidStudio 2021.2.1, as IntelliJ does not support the same file being in two different roots. It seems to be an old problem for IntelliJ, so maybe its just something that got reintroduced and will be fixed in a patch. youtrack.jetbrains.com/issue/…
    – arberg
    May 13, 2022 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.