在easymock中,对于mock对象的同一个方法,可以为每一次的调用定制不同的行为。在record阶段easymock会精确的记录我们录入的行为,基于每一次的方法调用。
这里有一个官网文档中的例子:
expect(mock.voteForRemoval(
"
Document
"
))
.andReturn(( byte ) 42 ).times( 3 )
.andThrow( new RuntimeException()).times( 4 )
.andReturn(( byte ) - 42 );
.andReturn(( byte ) 42 ).times( 3 )
.andThrow( new RuntimeException()).times( 4 )
.andReturn(( byte ) - 42 );
对于mock.voteForRemoval("Document")方法的调用,.andReturn((byte) 42).times(3) 表明前3次调用将返回42,.andThrow(new RuntimeException()).times(4)表示随后的4次调用(第4,5,6,7次)都将抛出异常,andReturn((byte) -42)表示第8次调用时将返回-42。
我们来验证一下:
public
class
ChangeBehehaviorTest
extends
Assert
{
private static interface Service {
public byte voteForRemoval(String name);
}
@Test
public void testExecute() {
final String name = "Document";
Service mock = EasyMock.createMock("service", Service.class);
EasyMock.expect(mock.voteForRemoval("Document")).andReturn((byte) 42).times(3).andThrow(new RuntimeException())
.times(4).andReturn((byte) -42);
EasyMock.replay(mock);
for (int i = 0; i < 3; i++) {
assertEquals(42, mock.voteForRemoval(name));
}
for (int i = 0; i < 4; i++) {
try {
mock.voteForRemoval(name);
fail("should throw RuntimeException");
} catch (RuntimeException e) {
}
}
assertEquals(-42, mock.voteForRemoval(name));
EasyMock.verify(mock);
}
}
private static interface Service {
public byte voteForRemoval(String name);
}
@Test
public void testExecute() {
final String name = "Document";
Service mock = EasyMock.createMock("service", Service.class);
EasyMock.expect(mock.voteForRemoval("Document")).andReturn((byte) 42).times(3).andThrow(new RuntimeException())
.times(4).andReturn((byte) -42);
EasyMock.replay(mock);
for (int i = 0; i < 3; i++) {
assertEquals(42, mock.voteForRemoval(name));
}
for (int i = 0; i < 4; i++) {
try {
mock.voteForRemoval(name);
fail("should throw RuntimeException");
} catch (RuntimeException e) {
}
}
assertEquals(-42, mock.voteForRemoval(name));
EasyMock.verify(mock);
}
}
测试案例顺利通过。