方法调用计数断言

时间:2012-04-04 06:52:52

标签: java unit-testing easymock powermock

我刚刚开始玩PowerMock和EasyMock,我对模拟方法调用的计算方式感到有些困惑。

示例代码:

class ClassToBeTested{
 private boolean toBeMocked(Integer i){
  return i%2==1; 
  }
 }

测试代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToBeTested.class)
public class ClassToBeTestedTest{

 private final Integer i=2;
 ClassToBeTested underTest;

 @Before
 public void setUp() throws Exception {
  underTest=PowerMock.createPartialMock(ClassToBeTested.class,
                    "toBeMocked");
  PowerMock.expectPrivate(underTest, "toBeMocked", i)
            .andReturn(true);
  PowerMock.replay(underTest);
 }
 @Test
 public dummyTest(){
  Assert.assertTrue(underTest.toBeMocked(i);
  //the call is: underTest.toBeMocked(2)
  //so the computation is return 2%2==1; google says it 0 :)
  //thus real method would return 0==1 (false)
  //mocked one will return true, assertion should pass, that's ok
  //RERUN ASSERTION
  Assert.assertTrue(underTest.toBeMocked(i);
  //method invocation count should be now 2
}

  @After
  public void tearDown() {
   PowerMock.verify(underTest);
   //WILL FAIL with exception saying
   //the mocked method has not been called at all
   //expected value (obvious) is one
}

我的问题是,为什么模拟的方法调用期望失败? 为什么验证ClassUnderTest会发现模拟方法根本没有被调用?

1 个答案:

答案 0 :(得分:1)

在将期望行更改为:

后,它适用于我
 PowerMock.expectPrivate(underTest, "toBeMocked", i).andReturn(true).times(2);

即使没有这种改变,也没有说嘲笑的母亲没有被召唤。它说

  Unexpected method call toBeMocked(2):
    toBeMocked(2): expected: 1, actual: 2

您使用的是最新的PowerMock和EasyMock版本吗?