Venkata Rama Raju
Venkata Rama Raju

Reputation: 1345

Spring data repository not injecting with @Mock in test case class returns null?

Repository object not injecting in testcase class. Here is my below test class code

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classesExternalProviderMain.class)
@ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE)
@WebAppConfiguration
public class EmployeeServiceTest {
@InjectMocks
EmployeeService employeeService; //not injected null 
@Mock
EmployeeRepository employeeRepository;//not injected null
@Test
public void testEmployee() {
    Mockito.when(employeeRepository.findByName(Stringname)).thenReturn(getEmployee());
    List<Employee> resultedTrackbles = employeeService.getEmployeeByName("mike");
}
private List<Employee> getEmployee(){
//here is the logic to return List<Employees>
}
}

Can you please help me how to inject my "EmployeeRepository" and Do need to write any additional logic.

Upvotes: 0

Views: 3494

Answers (1)

Tunaki
Tunaki

Reputation: 137299

That's because you are running your test with SpringJUnit4ClassRunner and not with MockitoJUnitRunner.

The mocks need to be initialized with MockitoAnnotations.initMocks:

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

Upvotes: 2

Related Questions