如何在 Android 项目中使用 PowerMock? [英] How to use PowerMock in Android projects?

查看:30
本文介绍了如何在 Android 项目中使用 PowerMock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的 Android 测试项目.我从 https://code.google.com/p/下载了 powermock-mockito-junit-1-1.5.zippowermock/下载/列表.我将所有库添加到测试项目的 libs 文件夹中.测试类是一个非常简单的对象:

I created a new Android test project. I downloaded powermock-mockito-junit-1-1.5.zip from https://code.google.com/p/powermock/downloads/list. I added all of the libraries to the test project's libs folder. The test class is a very simple object:

package com.test.test;

import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import android.util.Log;

@RunWith(PowerMockRunner.class)
public class TestTestAndroid {

    public void testRuns() {
        Log.e("test", "Test case is called");
    }
}

然后,我尝试从 Eclipse 运行项目,或者从命令行创建项目.我得到同样的错误:

Then, I try running the project from Eclipse, or making the project from the command line. I get the same error:

转Dalvik格式失败:无法执行dex:多个dex文件定义Lorg/hamcrest/Description;

事实证明,junit-4.8.2.jarmockito-all-1.9.5.jar 都定义了 org.hamcrest.Description.出于显而易见的原因,我必须包含 Mockito jar - 我需要 Mockito.Android 提供了不同版本的 JUnit,但它是不包含 @RunWith 注释的旧版本.

As it turns out, both junit-4.8.2.jar and mockito-all-1.9.5.jar define org.hamcrest.Description. I must include the Mockito jar for obvious reasons - I need Mockito. A different version of JUnit is provided by Android, but it is an old version that does not include the @RunWith annotation.

有人可以回答如何在 Android 项目中使用 powermock 和 mockito,而不会出现 org.hamcrest.Description 冲突的问题吗?

Can someone answer how to use powermock and mockito in an Android project, without the conflicting org.hamcrest.Description problem?

推荐答案

抱歉,你不能在 Dalvik VM 中使用 PowerMock.

Sorry, you can't use PowerMock in the Dalvik VM.

PowerMock 通过在使用 的自定义 ClassLoader 下运行您的测试来工作Javassist 来修改你的类的字节码.这在普通 JVM 上可以正常工作,但在 Dalvik 上,字节码和类格式不同,所以这种方法不起作用.需要重写 PowerMock 以使用 Dexmaker 而不是 Javassist - 这绝对不是微不足道的,并且我在 PowerMock 问题列表上没有看到类似的内容.

PowerMock works by running your test under a custom ClassLoader which uses Javassist to modify the bytecode of your classes. This works okay on a normal JVM, but on Dalvik the bytecode and class format are different, so this approach doesn't work. PowerMock would need to be rewritten to use Dexmaker instead of Javassist - this would be decidedly non-trivial, and I don't see anything like this on the PowerMock issues list.

这篇关于如何在 Android 项目中使用 PowerMock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆