EasyMock“意外的方法调用”尽管期望方法声明 [英] EasyMock "Unexpected method call" despite of expect method declaration

查看:115
本文介绍了EasyMock“意外的方法调用”尽管期望方法声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My EasyMock's expected method is perceived as unexpected, although I do not use and strict mocks, and the method is already declared before being replied.

测试在此失败代码行:

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 方法

Easymock expects the registerReceiver method to be called with exact parameter with which it is told to expect,

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

So to avoid this ,while expecting any method and writing its behaviour, use anyObject() method like this:-

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

easymock理解,当对象的任何对象都必须模拟对预期方法的所有调用时, IntentFilter 作为参数传递

by this, easymock understands that it has to mock all the calls to expected method, when any object of IntentFilter is passed as a parameter

希望这会有所帮助!
祝你好运!

Hope this helps! Good luck!

这篇关于EasyMock“意外的方法调用”尽管期望方法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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