Dependency Injection by constructor - Mockito tests

Viewed 48

I am dealing with following problem I created a service class that has a repository (Spring Data) as dependency, I am injecting by constructor. In this example I am using Lombok

Service Class

Repository Interface

I would like to know how can I test it with Mockito, I tried this way but it didn't work, the repository interface passed by parameter is getting null at the constructor.

I remove the Lombok to be possible to see the value getting null at the constructor.

Test Class

Service Class

If I change the dependency injection to @Autowired it works but I want to know how to test it this way.

Thank you so much I am a beginner on that...

2 Answers

You need not initialize the AuthorService class. Also, you need to specify that the response method is a mock as well. You can do it as follows:

@Mock
private AuthorRepository repo;

@InjectMocks
private AuthorService authorService;

   @Test
   public void testMethod(){
   Mockito.when(authorRepository.findByNameContaining(ArgumentMatchers.any()).thenReturn(authorList);
   //your assertions goes here

   }
Related