ape*_*x39 5 java android unit-testing easymock intentfilter
尽管我不使用和严格的模拟,但我的EasyMock的预期方法被认为是意外的,并且该方法已在声明之前进行了声明。
测试在以下代码行中失败:
Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Run Code Online (Sandbox Code Playgroud)
测试:
@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
}
Run Code Online (Sandbox Code Playgroud)
错误我得到:
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
Run Code Online (Sandbox Code Playgroud)
当你写类似的东西时,
expect(contextMock.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)))
.andReturn(someIntent1).once();
Run Code Online (Sandbox Code Playgroud)
Easymock期望registerReceiver使用被告知期望的确切参数来调用该方法,
因此,为避免这种情况,在期望任何方法并编写其行为的同时,请使用anyObject()方法,如下所示:
expect(contextMock.registerReceiver(null, EasyMock.anyObject(IntentFilter.class)))
.andReturn(someIntent1).once();
Run Code Online (Sandbox Code Playgroud)
通过这种方式,easymock了解到,当任何对象IntentFilter作为参数传递时,它必须模拟对预期方法的所有调用。
希望这可以帮助!祝好运!
| 归档时间: |
|
| 查看次数: |
14413 次 |
| 最近记录: |