简体   繁体   中英

Unit test with JUnit in Android with Gradle

I'm trying to set up Junit tests to test my Java code in an android project. I can't seem to get it working with the Gradle build.

I have set up one test as an example for now. My project is legacy which I ported to use Gradle, so I've defined the source sets and the structure rather than move the files into the new directory format.

When I run the build or just UnitTest the output is Build Successful, but it hasn't actually run my test unit test. Android studio does not seem to recognise the file as java either and does not show errors/ code completion on my ExampleTest.java file.

Project
  -> Module
     -> assets
     -> build
     -> gen
     -> libs
     -> res
     -> src
     -> tests

My gradle build file:

    buildscript {
    repositories {
        mavenCentral()
        maven { url 'http://repo1.maven.org/maven2' }
        maven { url 'http://download.crashlytics.com/maven' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:+'
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }
}

apply plugin: 'android'
apply plugin: 'crashlytics'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 20
    buildToolsVersion '20.0.0'


    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 20
        versionCode 47
        versionName '2.1'

    }
    buildTypes {
        release {
            runProguard true
            zipAlign true
            proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
            proguardFile 'proguard-project.txt'
        }
        debug {
            runProguard false
        }
    }

    productFlavors {
        defaultFlavor {
            proguardFile 'proguard-project.txt'
        }
    }

    signingConfigs {
        debug {
            storeFile file('../debug.keystore')
        }

        release {
            storeFile file("XX")
            storePassword "XX"
            keyAlias "XX"
            keyPassword "XX"
        }
    }

    sourceSets {

        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']

        }

        unitTest {
            java.srcDir file('tests')
            resources.srcDir file('test/resources')
        }

    }
}


sourceSets {
    unitTest {
        java.srcDir file('test')
        resources.srcDir file('test/resources')
    }
}

dependencies {
    compile 'com.viewpagerindicator:library:2.4.1@aar'
    compile 'com.crashlytics.android:crashlytics:1.+'
    unitTestCompile 'junit:junit:4.1+'
    unitTestCompile files("$buildDir/intermediates/classes/debug")
}


configurations {
    unitTestCompile.extendsFrom runtime
    unitTestRuntime.extendsFrom unitTestCompile
}

task unitTest(type:Test, dependsOn: assemble) {
    description = "run unit tests"
    testClassesDir = project.sourceSets.unitTest.output.classesDir
    classpath = project.sourceSets.unitTest.runtimeClasspath
}


// bind to check
build.dependsOn unitTest

Do the following to your gradle script. This will allow you to run your tests within the JVM, which means not having to run the emulator or run the tests on a device.

At the top:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.robolectric:robolectric-gradle-plugin:0.12.+'
    }
}

New plugin:

apply plugin: 'robolectric'

And near the bottom:

robolectric {

    //configure the set of classes for JUnit tests
    include '**/*Test.class'

    //configure whether failing tests should fail the build
    ignoreFailures false

}

And add the following dependencies:

androidTestCompile ('junit:junit:4.11')
androidTestCompile ('org.robolectric:robolectric:2.3') {
    exclude module: 'classworlds'
    exclude module: 'maven-artifact'
    exclude module: 'maven-artifact-manager'
    exclude module: 'maven-error-diagnostics'
    exclude module: 'maven-model'
    exclude module: 'maven-plugin-registry'
    exclude module: 'maven-profile'
    exclude module: 'maven-project'
    exclude module: 'maven-settings'
    exclude module: 'nekohtml'
    exclude module: 'plexus-container-default'
    exclude module: 'plexus-interpolation'
    exclude module: 'plexus-utils'
    exclude module: 'wagon-file'
    exclude module: 'wagon-http-lightweight'
    exclude module: 'wagon-http-shared'
    exclude module: 'wagon-provider-api'
    exclude group: 'com.android.support', module: 'support-v4'
}

Then start writing your tests in your tests folder. As you can see I set up a filter so only classes that start with Test.class are included in the test suite. Be sure to put the following annotations on any of these test classes: (be sure to change the url for the manifest file as it would be different for you from what is written)

@RunWith(RobolectricTestRunner.class)
@Config(manifest = "./src/main/AndroidManifest.xml", emulateSdk = 18)
class FirstTest {
    // tests go here
}

Finally, run the tests with ./gradlew test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM