Question

My understanding of JMockit is that it will replace all instances of a mocked object with a mock (unless you tell it otherwise).

Hence I am perplexed to be getting a NPE after instantiating an object I'm attempting to mock.

The purpose of the test is not to investigate the object causing the NPE, but I do need to mock it in order to carry out the test as it carrys out some database actions to validate some input.

My code under test is like this (not copy pasta, as it's work code, but should highlight the issue nonetheless):

public class ClassToTest{

    public execute(){
       MyDependency myDep = getDependency();

        myDep.doSomething(); //I get a NPE here, implying getDependency returned null 
    }

    protected MyDependency getDependency(){
        return new MyDependency("an Arg", "another Arg");
    }

}

My Test method:

@Test
public void testCreateHorseDogMeetingByCodeDataProviderTruncated()
    throws IllegalArgumentException, SQLException,
    IllegalCountryLocationCombo, MEPException {

    // Arrange
    ClassToTest myClass = new ClassToTest();

    new NonStrictExpectations() {

        MyDependency mockDep;

        {
            //Set up my expectations, not related to MyDependency
        }
    };

    // Act
    myClass.execute();

    // Assert
    new Verifications() {
        {
            //some verification stuff
        }
    };
}

Can anyone help me fix this NPE issue so I can finish my test?

Was it helpful?

Solution

Turns out I was accidentally instantiating a subclass of ClassToTest which overridded the implementation of getDependency and causing the null value to appear. Must have been an autocomplete thing.

OTHER TIPS

Is MyDependency an interface? You may need to mock the concrete class as well.

You can also try putting MyDependency mockDep in the argument list of the test function. Then you'll have the mocked object for the Verification step too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top