getting gradle to execute JUnit Test (Android app,

2019-07-02 03:20发布

问题:

I am currently working on an android app and lately switched from Eclipse to Android Studio (wasn't my idea;)). However I want to configure a jenkins server to run JUnit Tests and other tests on a regularly basis. To achieve this, I try to configure a gradle buidlfile. Here is my setup:

Directory structure:

-app

    -src
        -main
        -test

The build.gradle file: (located in "src/build.gradle)

    apply plugin: 'android'

    sourceSets {
        unitTest {
            java.srcDir file('src/test/java/[appName]/app')
        }
    }

    android {
        compileSdkVersion 19
        buildToolsVersion '19.0.3'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 19
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                runProguard false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
        sourceSets {
            instrumentTest.setRoot('src/test')
        }
    }

    task unitTest(type:Test) {
        testClassesDir = sourceSets.unitTest.output.classesDir
        classpath = sourceSets.unitTest.runtimeClasspath
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:support-v13:+'
        compile 'com.android.support:appcompat-v7:+'
        compile 'com.android.support:support-v4:+'

        unitTest 'junit:junit:4.10'
    }

Testclass MainActivityTest.java

    package [appName].app;

    import android.test.InstrumentationTestCase;
    import junit.framework.Assert;

    public class MainActivityTest extends InstrumentationTestCase{

        public void testMain(){
            Assert.assertEquals(1,2);
        }
    }

and the most important piece, the error message:

    Error:(41, 0) Build script error, unsupported Gradle DSL method found: 'unitTest()'!

It is my first time working with gradle and Android Studio and I have really no clue what I am doing wrong. On the internet I only find people with similar problems, but no one with a solution which worked for me. I'd be really glad if you could point me in the right direction!

Regards

回答1:

The error message tell that there is no such property unitTest. Test dependency are declared with instrumentTest (old) or androidTest (New).

Android sdk comes already with a junit 3 dependency. So just remove that line



回答2:

Unit testing doesn't appear to work out of the box in Android Studio. I have a working Gradle configuration that runs unit tests using Robolectric after some minor configurations.

See: Gradlectric

Also to specify a different test folder you need to instead use androidTest:

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