2

So I have a library module that wraps an API, and I want to write some tests. I want to import things like JUnit and MockWebServer, but only for the test sourceSet, and not for the androidTest one, as I want to use the former because the latter would cause the tests to be run in an android device or AVD, which I do not want. Therefore, I have this in my gradle file:

sourceSets {
    main {
        test {
            setRoot('src/test')
        }
    }
}

...

dependencies {
    ...
    testCompile 'junit:junit:4.12'
    testCompile 'com.squareup.okhttp:mockwebserver:2.4.0'
}

However, this will not work, and instead I will have to import the dependencies as androidTestCompile ones. Why is this?

1 Answers1

1

You should have a structure like this:

root
  module
    src
      main
      test

And all you need in your build.gradle is (without setting source sets):

dependencies {
    // Unit testing dependencies.
    testCompile 'junit:junit:4.12'
    testCompile 'com.squareup.okhttp:mockwebserver:2.4.0'
}

You can check in the official repo from Google:

If you would like to use unit test and Instrumentation tests you should have:

root
  module
    src
      main
      test
      androidTest

In this case your build.gradle should be:

dependencies {

    // Dependencies for local unit tests
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-all:1.10.19'
    testCompile 'org.hamcrest:hamcrest-all:1.3'

    // Android Testing Support Library's runner and rules
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'

}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 2
    Gabriele already described it pretty good. For unit testing you also have to switch the build variant, like described here: http://stackoverflow.com/questions/31468012/unit-testing-in-android-studio/31468895#31468895 – Rich Aug 25 '15 at 09:19
  • Yeah Gabriele's stuff was already working for me, but the build variant happened to be the sin, forgot about it. – Jorge Antonio Díaz-Benito Aug 25 '15 at 10:04