Search code examples
javaunit-testingmockingjmockit

Can JMockit initiate mock objects with argument constructor?


When I put the @Mocked annotation on a object which has only constructor with parameters, will this object be initiated rightly?


Solution

  • When I put the @Mocked annotation on a object which has only constructor with parameters, will this object be initiated rightly?

    No.

    A mock will be created that has the same interface. That means it will have the same public methods and if the test class is in the same package it will also have the same protected and package private methods accessible.

    This mock will not invoke the real methods of the mocked class (unless you configure it so).

    This means that for every method that is expected to be called by your code under test (cut) and that has a return value defined you have to configure your mock so that is returns a value your cut shall work with in that particular test.

    This configurable return values and the verify capabilities of the mocks are the reason why we use mocking frameworks.


    Attention

    If you want to mock the call to a method which accesses a member initialized by the mocked classes constructor you have to use the form

    doReturn(SOME_VALUE).when(mock).methodToBeCalledByYourCut();
    

    because the form

     when(mock.methodToBeCalledByYourCut()).thenReturn(SOME_VALUE);
    

    will raise a NullPointerException in that special case.