Reputation: 2043
I have create one parameterized class that takes two params. One is type of string and another is type of List of Abstract class. Class constructor looks like below code.
public TestService(Tenant tenant, List<AbstractService> testServices) {
testServicesMap = testServices.stream().collect(Collectors.toMap(AbstractService::getType, Function.identity()));
}
now I want to write Junit test case for this class and for that I have following piece of code.
@Mock
protected Tenant tenant;
@Mock
private List<AbstractService> testServices;
@InjectMocks
private TestService testService;
@Before
public void setup() {
testServices.add(new JobService(new JobEventService()));
testServices.add(new ApplicationService(new ApplicationEventService()));
testServices.add(new UserService(new UserEventService()));
// notificationService = new NotificationService(tenant, notificationServices);
// MockitoAnnotations.initMocks(notificationService);
}
I also tried to enabled two commented lines but its now working. Following is error that system throw on start.
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'notificationService' of type 'class com.test.TestService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : `null`.
Could someone help on this ?
Upvotes: 0
Views: 2299
Reputation: 10695
The problem is that you try to mock the list, and list.stream() is called, which in the mock default returns null.
A common solution from the duplicate questions is to use a @Spy of the list.
Upvotes: 0
Reputation: 3134
you are mixing mocks with real objects, because you create a mock of list but then call add
method on that list and then you expect stream()
to work as usually.
Mockito mocks don't do anything by default so you have to tell it:
Mockito.when(testServices.stream())
.thenReturn(Stream.of(new JobService(new JobEventService())));
or better in your case is to remove @Mock
from testServices
and assign it a new ArrayList
Upvotes: 1