Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method invocation count Assertion

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?

like image 473
wilu Avatar asked May 21 '26 20:05

wilu


1 Answers

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?

like image 165
artbristol Avatar answered May 23 '26 09:05

artbristol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!