Reputation: 25
I'm trying to mock my service class but I can't mock my service. The service class:
@Service
class SomeService {
private final Mapper mapper;
private final Client sourceClient;
private final Client destinationClient;
public SomeService(Configuration configuration, Mapper mapper) {
this.mapper = mapper;
this.sourceClient = configuration.getSourceClient();
this.destinationClient = configuration.getDestinationClient();
}
private Object fetch() {
sourceClient.getData();
}
public List<MyClass> doLogic() {
// do some logic here...
Object dataFromClient = fetch()
}
}
@ExtendWith(MockitoExtension.class)
class SomeServiceTest {
@InjectMocks
private SomeService someService;
@Mock
private Client sourceClient;
@Mock Client destinationClient;
@Mock Configuration configuration;
@Mock Mapper mapper;
@Test
void test() {
// given
when(sourceClient.getData().getItems()).thenReturn(preparedData());
// when
someService.doLogic();
}
private Object prepareData() {
return new Object();
}
I'm getting NullPointerException as it is now. I've noticed that the source of the problem is to call method getItems() in 'when(sourceClient.getData().getItems())'. When there is just getData() there is no NullPointerException but I would like to use getData().getItems(). Is there any way to mock or spy on that methods ? I would like to avoid mocking just getData() because of the object required to mock it.
Upvotes: 0
Views: 1185
Reputation: 38290
You are using a mock of Configuration
,
but you are not stubbing either the
configuration.getSourceClient()
method or
the configuration.getDestinationClient()
method.
Because of this,
sourceClient
is null in the SomeService.fetch()
method.
Upvotes: 1
Reputation: 146
@ExtendWith(MockitoExtension.class) indicates you are using junit5. so make sure you also use the @Test annotation from junit5 and not junit4
Upvotes: 0