模拟对象无法使用这是我的以下代码
@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>
}
}
因此,在测试用例中是否需要任何其他逻辑来获取模拟对象。
最佳答案
问题是您没有嘲笑电话
employeeRepository.findByName("mike")
但你在嘲笑
employeeRepository.findByName(null)
因为您的变量
name
从未初始化。将您的代码更改为:Mockito.when(employeeRepository.findByName("mike")).thenReturn(getEmployee());