2012-04-04 52 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