#14 Stub exception causes NPE

EasyMock_CE_2.5
closed
5
2012-10-05
2008-12-08
gubespam
No

Versions Affected:

EasyMock Class Extension 2.3 and 2.4

Scenerio:

When using EasyMock ClassExtension to create a stub version of an exception type that is thrown during a test by a mock collaborator of the class under test, EasyMock itself generates a NPE, instead of throwing the stub exception from the mock collaborator.

Example:

See attached. Can be run as a TestNG or JUnit test case.

Current Workaround:

When setting up the stub exception, include the following behavior:

EasyMock.expect( exception.fillInStackTrace() ).andReturn( exception );

Possible Solution:

Check whether the Throwable returned by t.getThrowable() is itself a mock object. If so, skip the fillInStackTrace() call before rethrowing it.

Discussion

  • gubespam
    gubespam
    2008-12-08

    Example code

     
    Attachments
  • gubespam
    gubespam
    2008-12-08

    Stack trace of NPE

     
    Attachments
  • gubespam
    gubespam
    2008-12-08

    File Added: stack_trace.txt

     
  • Henri Tremblay
    Henri Tremblay
    2008-12-10

    Hum... I'm not sure how useful it is to mock an exception. One the other hand, you're right, it fails. And I guess some exceptions are hard to instantiate. Somebody already raised that issue once and I told him to do your exact workaround.

    From there, your solution is good but inapplicable since standard EasyMock isn't aware of the class extension. So (for now) solutions are:

    1- Remove completly the fillInStackTrace. Works fine except the real exceptions will show EasyMock inner classes (which is what the fillInStackTrace is avoiding)
    2- Hack something that still allows EasyMock to know it's a mock
    3- Provide a default behavior for fillInStackTrace

    1 is the easiest, 3 doesn't seem bad. 2 is not really clean.

    Let's see

     
  • Henri Tremblay
    Henri Tremblay
    2008-12-10

    I actually found something better. First, a better workaround for you would be to do

    createNiceMock(RuntimeException.class, new Method[0]);

    It creates a mock with no method mocked. So the fillInStackTrace will behave normally and the test pass.

    Then, my final solution is to call the normal fillInStackTrace when it's called by EasyMock internal code. It's kinda tricky to do but works fine.