Junit Mockito NullPointerException for Mock for constructor based autowiring












0















I'm trying to test the implementation class, in which I'm creating a constructor based autowiring for the Interface.
I'm not suppose to change this class or the way it's autowired.



While writing test cases for the implementation class I'm getting NullPointerException because the object created in Implementation class
has different object reference and the mock object has different reference value.



Could anyone please tell me how to mock the object.



Implementation class



public class ImplementationClass implements ClientClass {

private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;

@Autowired
BBB bbb;

@Autowired
CCC ccc;

public DomainClass getDetails( String Id ) {
// aaa, bbb, ccc usage
DomainClass getDetDocument =
repositoryInterface.findById( Id ).orElse( null );

}


Unit Test Class



@Mock
RepositoryInterface repositoryInterface;

@Mock
DomainClass DomainClass;

@Mock
AAA aaa;

@Mock
BBB bbb;

@Mock
CCC ccc;

@InjectMocks
ImplementationClass implementationClass;

@Before
public void setUp() {
MockitoAnnotations.initMocks( this );
}

@Test
public void getDetTest() {
DomainClass dc = new DomainClass();
dc.setId( "Id-123456789" );
dc.setDetailsList( <Some list> );

Optional<DomainClass> c1 = Optional.of( dc );
// when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
DomainClass c2 = implementationClass.getDetails( "Id-123456789" );

assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}


UPDATE : While debugging the Test class, the object repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
creates a reference value (23425634534@2005) and when the
ImplementationClass is called the repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
in ImplementationClass has a reference value (23425634534@1879). Because of this I'm getting null for getDetDocument.










share|improve this question




















  • 1





    When asking about an exception, always post the complete stack trace of the exception.

    – JB Nizet
    Nov 20 '18 at 6:57











  • It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

    – Sam
    Nov 21 '18 at 5:14
















0















I'm trying to test the implementation class, in which I'm creating a constructor based autowiring for the Interface.
I'm not suppose to change this class or the way it's autowired.



While writing test cases for the implementation class I'm getting NullPointerException because the object created in Implementation class
has different object reference and the mock object has different reference value.



Could anyone please tell me how to mock the object.



Implementation class



public class ImplementationClass implements ClientClass {

private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;

@Autowired
BBB bbb;

@Autowired
CCC ccc;

public DomainClass getDetails( String Id ) {
// aaa, bbb, ccc usage
DomainClass getDetDocument =
repositoryInterface.findById( Id ).orElse( null );

}


Unit Test Class



@Mock
RepositoryInterface repositoryInterface;

@Mock
DomainClass DomainClass;

@Mock
AAA aaa;

@Mock
BBB bbb;

@Mock
CCC ccc;

@InjectMocks
ImplementationClass implementationClass;

@Before
public void setUp() {
MockitoAnnotations.initMocks( this );
}

@Test
public void getDetTest() {
DomainClass dc = new DomainClass();
dc.setId( "Id-123456789" );
dc.setDetailsList( <Some list> );

Optional<DomainClass> c1 = Optional.of( dc );
// when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
DomainClass c2 = implementationClass.getDetails( "Id-123456789" );

assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}


UPDATE : While debugging the Test class, the object repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
creates a reference value (23425634534@2005) and when the
ImplementationClass is called the repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
in ImplementationClass has a reference value (23425634534@1879). Because of this I'm getting null for getDetDocument.










share|improve this question




















  • 1





    When asking about an exception, always post the complete stack trace of the exception.

    – JB Nizet
    Nov 20 '18 at 6:57











  • It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

    – Sam
    Nov 21 '18 at 5:14














0












0








0








I'm trying to test the implementation class, in which I'm creating a constructor based autowiring for the Interface.
I'm not suppose to change this class or the way it's autowired.



While writing test cases for the implementation class I'm getting NullPointerException because the object created in Implementation class
has different object reference and the mock object has different reference value.



Could anyone please tell me how to mock the object.



Implementation class



public class ImplementationClass implements ClientClass {

private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;

@Autowired
BBB bbb;

@Autowired
CCC ccc;

public DomainClass getDetails( String Id ) {
// aaa, bbb, ccc usage
DomainClass getDetDocument =
repositoryInterface.findById( Id ).orElse( null );

}


Unit Test Class



@Mock
RepositoryInterface repositoryInterface;

@Mock
DomainClass DomainClass;

@Mock
AAA aaa;

@Mock
BBB bbb;

@Mock
CCC ccc;

@InjectMocks
ImplementationClass implementationClass;

@Before
public void setUp() {
MockitoAnnotations.initMocks( this );
}

@Test
public void getDetTest() {
DomainClass dc = new DomainClass();
dc.setId( "Id-123456789" );
dc.setDetailsList( <Some list> );

Optional<DomainClass> c1 = Optional.of( dc );
// when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
DomainClass c2 = implementationClass.getDetails( "Id-123456789" );

assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}


UPDATE : While debugging the Test class, the object repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
creates a reference value (23425634534@2005) and when the
ImplementationClass is called the repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
in ImplementationClass has a reference value (23425634534@1879). Because of this I'm getting null for getDetDocument.










share|improve this question
















I'm trying to test the implementation class, in which I'm creating a constructor based autowiring for the Interface.
I'm not suppose to change this class or the way it's autowired.



While writing test cases for the implementation class I'm getting NullPointerException because the object created in Implementation class
has different object reference and the mock object has different reference value.



Could anyone please tell me how to mock the object.



Implementation class



public class ImplementationClass implements ClientClass {

private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;

@Autowired
BBB bbb;

@Autowired
CCC ccc;

public DomainClass getDetails( String Id ) {
// aaa, bbb, ccc usage
DomainClass getDetDocument =
repositoryInterface.findById( Id ).orElse( null );

}


Unit Test Class



@Mock
RepositoryInterface repositoryInterface;

@Mock
DomainClass DomainClass;

@Mock
AAA aaa;

@Mock
BBB bbb;

@Mock
CCC ccc;

@InjectMocks
ImplementationClass implementationClass;

@Before
public void setUp() {
MockitoAnnotations.initMocks( this );
}

@Test
public void getDetTest() {
DomainClass dc = new DomainClass();
dc.setId( "Id-123456789" );
dc.setDetailsList( <Some list> );

Optional<DomainClass> c1 = Optional.of( dc );
// when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
DomainClass c2 = implementationClass.getDetails( "Id-123456789" );

assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}


UPDATE : While debugging the Test class, the object repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
creates a reference value (23425634534@2005) and when the
ImplementationClass is called the repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
in ImplementationClass has a reference value (23425634534@1879). Because of this I'm getting null for getDetDocument.







java spring-boot junit mocking mockito






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 10:16







Sam

















asked Nov 20 '18 at 6:14









SamSam

124214




124214








  • 1





    When asking about an exception, always post the complete stack trace of the exception.

    – JB Nizet
    Nov 20 '18 at 6:57











  • It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

    – Sam
    Nov 21 '18 at 5:14














  • 1





    When asking about an exception, always post the complete stack trace of the exception.

    – JB Nizet
    Nov 20 '18 at 6:57











  • It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

    – Sam
    Nov 21 '18 at 5:14








1




1





When asking about an exception, always post the complete stack trace of the exception.

– JB Nizet
Nov 20 '18 at 6:57





When asking about an exception, always post the complete stack trace of the exception.

– JB Nizet
Nov 20 '18 at 6:57













It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

– Sam
Nov 21 '18 at 5:14





It's a UserDefined Exception i'm getting in the console. But while debugging I'm getting null value for the statement DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null ); in Implementation class. Thats because, repositoryInterface object reference value is different in Implementation class and in Test class.

– Sam
Nov 21 '18 at 5:14












1 Answer
1






active

oldest

votes


















0














After all the research, got it working by changing the way the constructor was creating the object.



// @Mock //removed this annotation
RepositoryInterface repositoryInterface;


@Before
public void setUp() {
repositoryInterface = mock(RepositoryInterface.class)
ImplementationClass = new ImplementationClass(repositoryInterface);
MockitoAnnotations.initMocks( this );
}


Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387246%2fjunit-mockito-nullpointerexception-for-mock-for-constructor-based-autowiring%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    After all the research, got it working by changing the way the constructor was creating the object.



    // @Mock //removed this annotation
    RepositoryInterface repositoryInterface;


    @Before
    public void setUp() {
    repositoryInterface = mock(RepositoryInterface.class)
    ImplementationClass = new ImplementationClass(repositoryInterface);
    MockitoAnnotations.initMocks( this );
    }


    Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html






    share|improve this answer




























      0














      After all the research, got it working by changing the way the constructor was creating the object.



      // @Mock //removed this annotation
      RepositoryInterface repositoryInterface;


      @Before
      public void setUp() {
      repositoryInterface = mock(RepositoryInterface.class)
      ImplementationClass = new ImplementationClass(repositoryInterface);
      MockitoAnnotations.initMocks( this );
      }


      Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html






      share|improve this answer


























        0












        0








        0







        After all the research, got it working by changing the way the constructor was creating the object.



        // @Mock //removed this annotation
        RepositoryInterface repositoryInterface;


        @Before
        public void setUp() {
        repositoryInterface = mock(RepositoryInterface.class)
        ImplementationClass = new ImplementationClass(repositoryInterface);
        MockitoAnnotations.initMocks( this );
        }


        Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html






        share|improve this answer













        After all the research, got it working by changing the way the constructor was creating the object.



        // @Mock //removed this annotation
        RepositoryInterface repositoryInterface;


        @Before
        public void setUp() {
        repositoryInterface = mock(RepositoryInterface.class)
        ImplementationClass = new ImplementationClass(repositoryInterface);
        MockitoAnnotations.initMocks( this );
        }


        Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 9:01









        SamSam

        124214




        124214
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387246%2fjunit-mockito-nullpointerexception-for-mock-for-constructor-based-autowiring%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()