Unable to mock mongoRepository instance

497 views Asked by At
import static org.mockito.Mockito.when;

import java.util.ArrayList;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.poc.kafka.mongo.entity.Employee;
import com.poc.kafka.mongo.repository.EmployeeMongoRepository;
import com.poc.kafka.mongo.service.EmployeeService;
import com.poc.kafka.mongo.service.EmployeeServiceImpl;

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class EmployeeServiceMockTests {
    @InjectMocks
    EmployeeService employeeService=new EmployeeServiceImpl();
    @Mock
    EmployeeMongoRepository employeeMongoRepository;
    
    @Test
    public void testFindAll() {
        when(employeeMongoRepository.findAll()).thenReturn(new ArrayList<Employee>());
        employeeService.findAll();
    }
}

I'm trying to mock employeeMongoRepository instance which is extended from MongoRepository class into service but unable to mock. mock object is getting as null. I'm using spring-boot-test, mockito and junit-vintage. Not sure whether i'm right?

1

There are 1 answers

0
Vitor Cavalcanti On

First of all, you're mixing JUnit 4 and 5 versions, as @ExtendWith annotation and MockitoExtension are for JUnit 5 tests.

After removing that, change your @RunWith annotation to:

@RunWith(SpringRunner.class)

You can check this information in the docs:

If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…Test annotations are already annotated with it.