java - EasyMock "Unexpected method call"尽管有 expect 方法声明

标签 java android unit-testing intentfilter easymock

我的 EasyMock 预期方法被认为是意外的,尽管我没有使用和严格模拟,并且该方法在被回复之前已经声明。

在这行代码中测试失败:

Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

测试:

@Before
public void setUp() {
    mocksControl = createControl();
    contextMock = mocksControl.createMock(Context.class);
    //(...)
}

@Test
public void test() {
    expect(contextMock.getApplicationContext()).andReturn(contextMock).anyTimes();
    expect(contextMock.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)))
        .andReturn(someIntent1).once();
    expect(contextMock.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)))
        .andReturn(someIntent2).once();
    mocksControl.replay();
    //(...) tested method is invoked on class under the test
}

我得到的错误:

java.lang.AssertionError: 
  Unexpected method call Context.registerReceiver(null, android.content.IntentFilter@c009614f):
    Context.registerReceiver(null, android.content.IntentFilter@c009614f): expected: 1, actual: 0
    Context.registerReceiver(null, android.content.IntentFilter@c009614f): expected: 1, actual: 0

最佳答案

当你写类似的东西时,

expect(contextMock.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)))
        .andReturn(someIntent1).once();

Easymock 期望调用 registerReceiver 方法时使用它被告知期望的确切参数,

因此,为了避免这种情况,在期望任何方法并编写其行为的同时,使用 anyObject() 方法,如下所示:-

expect(contextMock.registerReceiver(null, EasyMock.anyObject(IntentFilter.class)))
            .andReturn(someIntent1).once();

由此,当 IntentFilter 的任何对象作为参数传递时,easymock 明白它必须模拟所有对预期方法的调用

希望对您有所帮助! 祝你好运!

关于java - EasyMock "Unexpected method call"尽管有 expect 方法声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966388/

相关文章:

python - PyUnit - 如何对某个输入进入无限循环的方法进行单元测试?

unit-testing - 在单个单元测试失败时失败 TFS 构建

java - 增强的 for 循环 - JAVA

java - 为什么 Hashtable 不是 Java Collection 框架的一部分?

android - 微调器从顶部而不是底部打开

android - Jetpack compose 中 Unresolved 修改器方法引用

java - 无法在 log4j2 中使用 RollingFileAppender 写入日志

java - Java 7 中方法 pack() 中的 NullPointerException

java - 加载失败,请确认其已声明

angularjs - 访问外部元素的单元测试 Angular 指令