Mockito is not mocking out a member variable method return value












0















I have the following class that contains a member variable, but Mockito can't seem to mock the member variable's methods. Below is my System Under Test:



public class MessageConsumer {

private ConsumerResponse consumerResponse;
private NotificationConsumer notificationConsumer;

@Scheduled(cron = "${com.example.value}")
public void fetch() {
consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
}

public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
this.consumerResponse = consumerResponse;
}

public ConsumerResponse getConsumerResponse() {
return consumerResponse;
}
}


And the following is the relevant JUnit test for the class:



@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

@Mock
private ConsumerResponse consumerResponse;

@InjectMocks
private MessageConsumer messageConsumer;

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

//Failing unit test
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch()
}

}


As you can see, I've mocked the ConsumerResponse consumerResponse variable to return "200" when the consumerResponse.getResponseCode() method gets invoked. Instead, I'm getting a NullPointerException.



I'm pretty sure I mocked the member variable correctly and initialized it appropriately (initMocks). I've spent days trying to figure this out. Where am I going wrong?










share|improve this question

























  • can you share ConsumerResponse class?

    – GauravRai1512
    Nov 25 '18 at 7:48











  • @GauravRai1512 It's in an external library that I unfortunately do not have access to

    – prometheusnoob
    Nov 25 '18 at 7:51











  • @JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

    – prometheusnoob
    Nov 25 '18 at 7:53













  • You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

    – JB Nizet
    Nov 25 '18 at 7:53






  • 2





    Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

    – JB Nizet
    Nov 25 '18 at 7:55
















0















I have the following class that contains a member variable, but Mockito can't seem to mock the member variable's methods. Below is my System Under Test:



public class MessageConsumer {

private ConsumerResponse consumerResponse;
private NotificationConsumer notificationConsumer;

@Scheduled(cron = "${com.example.value}")
public void fetch() {
consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
}

public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
this.consumerResponse = consumerResponse;
}

public ConsumerResponse getConsumerResponse() {
return consumerResponse;
}
}


And the following is the relevant JUnit test for the class:



@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

@Mock
private ConsumerResponse consumerResponse;

@InjectMocks
private MessageConsumer messageConsumer;

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

//Failing unit test
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch()
}

}


As you can see, I've mocked the ConsumerResponse consumerResponse variable to return "200" when the consumerResponse.getResponseCode() method gets invoked. Instead, I'm getting a NullPointerException.



I'm pretty sure I mocked the member variable correctly and initialized it appropriately (initMocks). I've spent days trying to figure this out. Where am I going wrong?










share|improve this question

























  • can you share ConsumerResponse class?

    – GauravRai1512
    Nov 25 '18 at 7:48











  • @GauravRai1512 It's in an external library that I unfortunately do not have access to

    – prometheusnoob
    Nov 25 '18 at 7:51











  • @JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

    – prometheusnoob
    Nov 25 '18 at 7:53













  • You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

    – JB Nizet
    Nov 25 '18 at 7:53






  • 2





    Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

    – JB Nizet
    Nov 25 '18 at 7:55














0












0








0








I have the following class that contains a member variable, but Mockito can't seem to mock the member variable's methods. Below is my System Under Test:



public class MessageConsumer {

private ConsumerResponse consumerResponse;
private NotificationConsumer notificationConsumer;

@Scheduled(cron = "${com.example.value}")
public void fetch() {
consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
}

public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
this.consumerResponse = consumerResponse;
}

public ConsumerResponse getConsumerResponse() {
return consumerResponse;
}
}


And the following is the relevant JUnit test for the class:



@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

@Mock
private ConsumerResponse consumerResponse;

@InjectMocks
private MessageConsumer messageConsumer;

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

//Failing unit test
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch()
}

}


As you can see, I've mocked the ConsumerResponse consumerResponse variable to return "200" when the consumerResponse.getResponseCode() method gets invoked. Instead, I'm getting a NullPointerException.



I'm pretty sure I mocked the member variable correctly and initialized it appropriately (initMocks). I've spent days trying to figure this out. Where am I going wrong?










share|improve this question
















I have the following class that contains a member variable, but Mockito can't seem to mock the member variable's methods. Below is my System Under Test:



public class MessageConsumer {

private ConsumerResponse consumerResponse;
private NotificationConsumer notificationConsumer;

@Scheduled(cron = "${com.example.value}")
public void fetch() {
consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
}

public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
this.consumerResponse = consumerResponse;
}

public ConsumerResponse getConsumerResponse() {
return consumerResponse;
}
}


And the following is the relevant JUnit test for the class:



@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

@Mock
private ConsumerResponse consumerResponse;

@InjectMocks
private MessageConsumer messageConsumer;

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

//Failing unit test
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch()
}

}


As you can see, I've mocked the ConsumerResponse consumerResponse variable to return "200" when the consumerResponse.getResponseCode() method gets invoked. Instead, I'm getting a NullPointerException.



I'm pretty sure I mocked the member variable correctly and initialized it appropriately (initMocks). I've spent days trying to figure this out. Where am I going wrong?







java spring-boot junit mockito






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 7:42







prometheusnoob

















asked Nov 25 '18 at 7:36









prometheusnoobprometheusnoob

326




326













  • can you share ConsumerResponse class?

    – GauravRai1512
    Nov 25 '18 at 7:48











  • @GauravRai1512 It's in an external library that I unfortunately do not have access to

    – prometheusnoob
    Nov 25 '18 at 7:51











  • @JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

    – prometheusnoob
    Nov 25 '18 at 7:53













  • You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

    – JB Nizet
    Nov 25 '18 at 7:53






  • 2





    Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

    – JB Nizet
    Nov 25 '18 at 7:55



















  • can you share ConsumerResponse class?

    – GauravRai1512
    Nov 25 '18 at 7:48











  • @GauravRai1512 It's in an external library that I unfortunately do not have access to

    – prometheusnoob
    Nov 25 '18 at 7:51











  • @JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

    – prometheusnoob
    Nov 25 '18 at 7:53













  • You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

    – JB Nizet
    Nov 25 '18 at 7:53






  • 2





    Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

    – JB Nizet
    Nov 25 '18 at 7:55

















can you share ConsumerResponse class?

– GauravRai1512
Nov 25 '18 at 7:48





can you share ConsumerResponse class?

– GauravRai1512
Nov 25 '18 at 7:48













@GauravRai1512 It's in an external library that I unfortunately do not have access to

– prometheusnoob
Nov 25 '18 at 7:51





@GauravRai1512 It's in an external library that I unfortunately do not have access to

– prometheusnoob
Nov 25 '18 at 7:51













@JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

– prometheusnoob
Nov 25 '18 at 7:53







@JB Nizet But that shouldn't matter since the method I'm mocking out belongs to the consumerResponse object, right? -- isn't that the whole point of Mockito? (to isolate dependencies and make them do what you want them to?)

– prometheusnoob
Nov 25 '18 at 7:53















You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

– JB Nizet
Nov 25 '18 at 7:53





You're using notificationConsumer in your code, but it isn't mocked. So it's null. The SpringBootTest annotation is useless, too, since you're not running your test with the SpringRunner. So it doesn't have any effect.

– JB Nizet
Nov 25 '18 at 7:53




2




2





Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

– JB Nizet
Nov 25 '18 at 7:55





Precisely: you want to isolate the class under test (MessageConsumer) from its dependencies (NotificationConsumer). So you need to mock NotificationConsumer.

– JB Nizet
Nov 25 '18 at 7:55












1 Answer
1






active

oldest

votes


















3














As NotificationConsumer is also an external dependency for this class, you have to also mock this class as otherwise consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); will result into null within your test as you didn't mock the NotificationConsumer. In addition I would suggest not to use @SpringBootTest within this unit test as this annotation will boot the whole Spring context. The following snippet should help you:



@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

@Mock
private ConsumerResponse consumerResponse;

@Mock
private NotificationConsumer notificationConsumer;

@InjectMocks
private MessageConsumer messageConsumer;

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

@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch();
}

}





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%2f53465549%2fmockito-is-not-mocking-out-a-member-variable-method-return-value%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









    3














    As NotificationConsumer is also an external dependency for this class, you have to also mock this class as otherwise consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); will result into null within your test as you didn't mock the NotificationConsumer. In addition I would suggest not to use @SpringBootTest within this unit test as this annotation will boot the whole Spring context. The following snippet should help you:



    @RunWith(MockitoJUnitRunner.class)
    public class MessageConsumerTest {

    @Mock
    private ConsumerResponse consumerResponse;

    @Mock
    private NotificationConsumer notificationConsumer;

    @InjectMocks
    private MessageConsumer messageConsumer;

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

    @Test
    public void getResponseCodeShouldReturn200() {
    Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
    Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
    messageConsumer.fetch();
    }

    }





    share|improve this answer




























      3














      As NotificationConsumer is also an external dependency for this class, you have to also mock this class as otherwise consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); will result into null within your test as you didn't mock the NotificationConsumer. In addition I would suggest not to use @SpringBootTest within this unit test as this annotation will boot the whole Spring context. The following snippet should help you:



      @RunWith(MockitoJUnitRunner.class)
      public class MessageConsumerTest {

      @Mock
      private ConsumerResponse consumerResponse;

      @Mock
      private NotificationConsumer notificationConsumer;

      @InjectMocks
      private MessageConsumer messageConsumer;

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

      @Test
      public void getResponseCodeShouldReturn200() {
      Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
      Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
      messageConsumer.fetch();
      }

      }





      share|improve this answer


























        3












        3








        3







        As NotificationConsumer is also an external dependency for this class, you have to also mock this class as otherwise consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); will result into null within your test as you didn't mock the NotificationConsumer. In addition I would suggest not to use @SpringBootTest within this unit test as this annotation will boot the whole Spring context. The following snippet should help you:



        @RunWith(MockitoJUnitRunner.class)
        public class MessageConsumerTest {

        @Mock
        private ConsumerResponse consumerResponse;

        @Mock
        private NotificationConsumer notificationConsumer;

        @InjectMocks
        private MessageConsumer messageConsumer;

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

        @Test
        public void getResponseCodeShouldReturn200() {
        Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
        Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
        messageConsumer.fetch();
        }

        }





        share|improve this answer













        As NotificationConsumer is also an external dependency for this class, you have to also mock this class as otherwise consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); will result into null within your test as you didn't mock the NotificationConsumer. In addition I would suggest not to use @SpringBootTest within this unit test as this annotation will boot the whole Spring context. The following snippet should help you:



        @RunWith(MockitoJUnitRunner.class)
        public class MessageConsumerTest {

        @Mock
        private ConsumerResponse consumerResponse;

        @Mock
        private NotificationConsumer notificationConsumer;

        @InjectMocks
        private MessageConsumer messageConsumer;

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

        @Test
        public void getResponseCodeShouldReturn200() {
        Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
        Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
        messageConsumer.fetch();
        }

        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 10:21









        rieckpilrieckpil

        1,3111618




        1,3111618
































            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%2f53465549%2fmockito-is-not-mocking-out-a-member-variable-method-return-value%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







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'