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
顯示模擬方法根本沒有被調用?
**我的錯誤**我上面介紹的例子是在真實問題的誘餌上做出的,但不幸的是我**錯過了一個重要問題,可以解釋我的問題: – wilu 2012-04-04 09:33:07
**我的錯誤**例子I上面提到的是在真正的問題的baiss上,但不幸的是,我**錯過了一個重要的問題,解釋了我的問題:我的Test dummyMethod在實際的例子中被分爲兩個測試方法,運行相同的模擬方法。我的期望是,嘲笑的方法將只運行**一次**所有測試方法。我認爲**錯誤**比After方法在所有Test方法執行後將被調用**一次**。一個測試方法根本不調用模擬方法,所以實際的調用是O,預計爲1,因此我的問題是...... – wilu 2012-04-04 09:39:19