开发者

JMockit: Null Pointer Error When Mock Object Should Be Instatiated?

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,
    I开发者_Go百科llegalCountryLocationCombo, 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜