Search code examples
javaeasymock

What is the purpose of EasyMock.andVoid()?


The javadoc for EasyMock.andVoid() read's as follows

Records a call but returns nothing. Used to chain calls on void methods expectLastCall().andThrow(e).andVoid()

Returns:

this object to allow method call chaining.lockquote

Do you know any possible situation in which one needs this? What is the purpose of andVoid() in the above example?

Let us consider:

myMock.myMethod();
expectLastCall().andVoid().andThrow(e)

With myMethod having return type void. Then we could just omit the 'chain-element' andVoid.


Solution

  • It is really rare what you will need this. Because in most case you only need to call the void method to mock it. Like this

    MyClass myMock = mock(MyClass.class);
    myMock.myMethod();
    replay(myMock);
    myMock.myMethod(); // one call to myMethod expected
    verify(myMock);
    

    Which is a synonym of

    MyClass myMock = mock(MyClass.class);
    myMock.myMethod();
    expectLastCall();
    replay(myMock);
    myMock.myMethod(); // one call to myMethod expected
    verify(myMock);
    

    Then let's say you want the first call to myMethod to throw an exception and the second to respond normally, you can do.

    MyClass myMock = mock(MyClass.class);
    myMock.myMethod();
    expectLastCall().andThrow(new RuntimeException("test"));
    expectLastCall().andVoid();
    replay(myMock);
    try {
      myMock.myMethod(); // one call to myMethod will throw an exception
      fail("should throw");
    } catch(RuntimeException e) {}
    myMock.myMethod(); // the other will be normal
    verify(myMock);
    

    Or by chaining them

    MyClass myMock = mock(MyClass.class);
    myMock.myMethod();
    expectLastCall().andThrow(new RuntimeException("test")).andVoid();
    replay(myMock);
    try {
      myMock.myMethod(); // one call to myMethod will throw an exception
      fail("should throw");
    } catch(RuntimeException e) {}
    myMock.myMethod(); // the other will be normal
    verify(myMock);
    

    This use case is of course super rare but we still support it.