Reputation: 191
I want to test a service class which extends an abstract class using Mockito. My code looks like following :
public abstract class MyFooServiceAbstractClass {
@Autowired
private FooRepository fooRepository;
public save(FooEntity foo){fooRepository.save(foo);}
}
@Service
public class FooService extends MyFooServiceAbstractClass {
private final BarService barService;
public FooService(BarService barservice){
this.barService = barservice;
}
public void create(FooEntity fooEntity){
barService.returnSomething();
save(fooEntity);
}
}
Concerting the test, I am using MockitoEntension. the test is as following :
@ExtendWith(MockitoExtension.class)
public class FooServiceTest {
@InjectMocks
private FooService fooService;
@Mock
private FooRepository fooRepository;
@Mock
private BarService barService;
@Captor
private ArgumentCaptor<FooEntity> captor;
@Test
void test(){
// Given
FooEntity foo = new FooEntity();
when(barService.doSomething()).thenReturn(something);
// When
fooService.save(foo);
// Then
verify(fooRepository).save(captor.capture());
// assert goes here...
}
}
When debuging the test, fooRepository is null.
By changing the injection in FooService from constructor injection to Autowired, the mock fooRepository stops being null.
Using Autowired and constructor injections seems to be working fine when the spring context is created.
My question is : What is the difference between creating the mocks in mockito and creating the real beans ?
Upvotes: 0
Views: 117
Reputation: 174
From the given code above, I can see that the constructor for FooService does not accept an object for FooRepository. Can you please try the code in the following format ? (since you mentioned using Lombok, I have used lombok annotations)
@RequiredArgsConstructor
public abstract class MyFooServiceAbstractClass {
private final FooRepository fooRepository;
public save(FooEntity foo){fooRepository.save(foo);}
}
@Service
public class FooService extends MyFooServiceAbstractClass {
private final BarService barService;
public FooService(BarService barservice, FooRepository fooRepository){
super(fooRepository)
this.barService = barservice;
}
public void create(FooEntity fooEntity){
barService.returnSomething();
save(fooEntity);
}
}
Upvotes: 1