2012-04-04 51 views
3

我刚刚开始玩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

它的工作对我来说,改变期望行后:

PowerMock.expectPrivate(underTest, "toBeMocked", i).andReturn(true).times(2); 

即使没有改变,它没有说的嘲笑母亲不叫。它说

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

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

+0

**我的错误**我上面介绍的例子是在真实问题的诱饵上做出的,但不幸的是我**错过了一个重要问题,可以解释我的问题: – wilu 2012-04-04 09:33:07

+0

**我的错误**例子I上面提到的是在真正的问题的baiss上,但不幸的是,我**错过了一个重要的问题,解释了我的问题:我的Test dummyMethod在实际的例子中被分为两个测试方法,运行相同的模拟方法。我的期望是,嘲笑的方法将只运行**一次**所有测试方法。我认为**错误**比After方法在所有Test方法执行后将被调用**一次**。一个测试方法根本不调用模拟方法,所以实际的调用是O,预计为1,因此我的问题是...... – wilu 2012-04-04 09:39:19