Method invocation count Assertion

Go To StackoverFlow.com

3

I've just started playing with PowerMock and EasyMock and I'm a bit confused about the way mocked method invocations are counted.

Example code:

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

And the test code:

@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
}

And my question is, why does the mocked method invocation expectation fail? Why verifying ClassUnderTest reveals that mocked method wasn't called at all?

2012-04-04 06:52
by wilu


1

It works for me, after changing the expect line to:

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

Even without that change, it doesn't say the mocked mother wasn't called. It says

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

Are you using the most up to date PowerMock and EasyMock versions?

2012-04-04 08:22
by artbristol
My fault The example I presented above was made on the baiss of the real problem, but unfortunately I missed one important issue that explains my problem - wilu 2012-04-04 09:33
My fault The example I presented above was made on the baiss of the real problem, but unfortunately I missed one important issue that explains my problem: my Test dummyMethod in real example isdivided into two Test methods that run the same mocked method. My expectations is, the mocked method will be run only once by all Test methods. I thought wrongly than After method will be called once after the execution of all Test methods. One Test method doesn't call mocked method at all, so actual call is O, expected 1, thus my question.. - wilu 2012-04-04 09:39
Ads