AndroidStudio/Gradle with powermock

2019-02-05 10:50发布

I couldn't find any info on how to setup powermock with Android Studio/Gradle. Everything I've tried resulted in build exceptions.

Could anybody show a correct way to do it?

Thanks.

6条回答
你好瞎i
2楼-- · 2019-02-05 11:22

In the build script, add the following:

sourceSets {
    unitTest {
        java.srcDir file('*your test directory*') //for example: tests/java
    }
}

android {
    sourceSets {
        instrumentTest.setRoot('*your root test directory*') //for example: tests
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.11'
    testCompile 'org.powermock:powermock-mockito-release-full:1.4.9'
}

Then, do gradle unitTest from the command line.

Hope that works. If it doesn't, post the output of the command line.

查看更多
家丑人穷心不美
3楼-- · 2019-02-05 11:28

I have used same as @Bhargav used with some additional features added with it

  • code coverage for test case (if testCoverageEnabled is true, then it enable Jacoco tool)
  • unit test will test only your code and do not depend on any particular behaviour of Android platform by using (UnitTests.returnDefaultValues = true)

Add this marked lines in build.gradle to enable JUnit, PowerMockito, JaCoCo

enter image description here enter image description here

查看更多
家丑人穷心不美
4楼-- · 2019-02-05 11:32

I'm posting in order to help future readers, you need to add these dependencies for powermock in AS

testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock-api-mockito:1.6.2'
testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.2'
testCompile 'org.powermock:powermock-module-junit4-rule:1.6.2'
testCompile 'org.powermock:powermock-module-junit4:1.6.2'
查看更多
贪生不怕死
5楼-- · 2019-02-05 11:32
// mockito
testImplementation 'org.mockito:mockito-core:2.4.0'
androidTestImplementation 'org.mockito:mockito-core:2.4.0'
// PowerMock
testImplementation 'org.powermock:powermock-core:1.7.0RC2'
testImplementation 'org.powermock:powermock-module-junit4:1.7.0RC2'
testImplementation 'org.powermock:powermock-api-mockito2:1.7.0RC2'
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-05 11:43

Add the following lines to your dependencies{} block:

testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock:1.6.5'
testCompile 'org.powermock:powermock-module-junit4:1.6.5'

And if you would like to use PowerMockito, add the following line:

testCompile 'org.powermock:powermock-api-mockito:1.6.5'
查看更多
Rolldiameter
7楼-- · 2019-02-05 11:48

If you want to use more recent versions of Mockito, you can use something like this, which is adapted from the mockito 2 Powermock docs. Do make sure you use the right version of PowerMock for the given version of Mockito.

...
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:2.4.0"
testCompile 'org.powermock:powermock-module-junit4:1.7.0RC2',
            'org.powermock:powermock-api-mockito2:1.7.0RC2'
查看更多
登录 后发表回答