Reputation: 167
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?
Upvotes: 0
Views: 1455
Reputation: 12051
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();
}
}
Upvotes: 3