PowerMockito.whenNew 不适用于 android 的 Intent 类

Nit*_*ain 2 android powermock android-intent powermockito

我正在尝试使用模拟 Intent 对象,但是当使用来自 PowerMockito 的 whenNew 时,我无法模拟构造函数。我已经尝试了所有可能的参数组合,但它不起作用。

小智 5

我有一个类似的问题,在这个答案中找到了解决方案。

更具体地说:请尝试@PrepareForTest在测试或类级别添加注释,并为其提供构建您的 Intent 的类

public class SomeClassThatCreatesIntent {

    public void someMethodWithIntent() {
        Intent i = new Intent();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后测试类应该是这样的:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeClassThatCreatesIntent.class})
public class SomeClassThatCreatesIntentTest {

    @Test
    public void test() {
        // Some test that uses PowerMockito.whenNew(Intent.class)
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助。