我找不到有关如何在Android Studio/Gradle中设置PowerMock的信息。我尝试了一切,但都导致构建异常。
能否有人展示正确的做法?
谢谢。
我发帖是为了帮助未来的读者,你需要在AS中添加这些依赖项才能使用PowerMock。
testImplementation 'junit:junit:4.12'
testImplementation 'org.powermock:powermock-api-mockito:1.6.2'
testImplementation 'org.powermock:powermock-module-junit4-rule-agent:1.6.2'
testImplementation 'org.powermock:powermock-module-junit4-rule:1.6.2'
testImplementation 'org.powermock:powermock-module-junit4:1.6.2'
将以下代码添加到您的dependencies {}块中:
testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock:1.6.5'
testCompile 'org.powermock:powermock-module-junit4:1.6.5'
如果您想使用PowerMockito,请添加以下行:
testCompile 'org.powermock:powermock-api-mockito:1.6.5'
如果你想使用更高版本的Mockito,你可以像这样使用,这是从Mockito 2 Powermock文档中调整过来的。确保你使用与给定版本的Mockito相对应的正确版本的PowerMock
...
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'
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'
}
接下来,请从命令行执行gradle unitTest。
希望这能起作用。如果不行,请发布命令行的输出。
testCompile 'junit:junit:4.12'<br/> testCompile 'org.powermock:powermock-api-mockito:1.6.1'<br/> testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.1'<br/> testCompile 'org.powermock:powermock-module-junit4-rule:1.6.1'<br/> testCompile 'org.powermock:powermock-module-junit4:1.6.1'
<br/>
在这里得到了提示:https://code.google.com/p/android/issues/detail?id=147472。- 抱歉格式不好,我无法在评论中换行? - jokki// 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'
以下是我从所有可找到的答案中编译的示例,使用的是最新版本:
app\build.gradle
dependencies {
testImplementation group: 'junit', name: 'junit', version: '4.13'
...
testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.7'
testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.7'
}
Log
类被静态模拟了。import android.util.Log;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class})
public class DateUtilsTest {
@BeforeClass
public static void beforeClass() {
PowerMockito.mockStatic(Log.class);
}
...
}