模拟对象没有进入我的服务?

时间:2015-09-27 15:11:47

标签: java unit-testing mockito spring-data-jpa

模拟对象无法使用这是我的下面的代码

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classesExternalProviderMain.class)
@ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE)
@WebAppConfiguration
public class EmployeeServiceTest {

    @InjectMocks
    EmployeeService employeeService; 
    @Mock
    EmployeeRepository employeeRepository;
    String name;
    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    @Test
    public void testEmployee() {
        Mockito.when(employeeRepository.findByName(name)).thenReturn(getEmployee());
        List<Employee> resultedEmployees = employeeService.getEmployeeByName("mike");
    }
    private List<Employee> getEmployee(){
        //here is the logic to return List<Employees>
    }
}

public EmployeeServiceImpl implements EmployeeService{
    @Autowired
    EmployeeRepository employeeRepository;
    employeeService.
    public List<Employee> getEmployeeByName(String name){
        List<Employee> employees =  employeeRepository.findByName(name);
        //Here I does't want to hit the real database so I have mocked it in testcase but I am getting empty list when I debug it. So can you please tell me what i did wrong in my "EmployeeServiceTest" to get List<Employee>
    }
}

因此,在测试用例中需要任何额外的逻辑来获取模拟对象。

1 个答案:

答案 0 :(得分:2)

问题是你没有嘲笑电话

employeeRepository.findByName("mike")

但是你在嘲笑

employeeRepository.findByName(null)

因为您的变量name从未初始化。将您的代码更改为:

Mockito.when(employeeRepository.findByName("mike")).thenReturn(getEmployee());