Java 模拟对象没有进入我的服务?
模拟对象没有进入服务,下面是我的代码Java 模拟对象没有进入我的服务?,java,unit-testing,mockito,spring-data-jpa,Java,Unit Testing,Mockito,Spring Data Jpa,模拟对象没有进入服务,下面是我的代码 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classesExternalProviderMain.class) @ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE) @WebAppConfiguration public class EmployeeServiceTest { @Inje
@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>
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classesExternalProviderMain.class)
@ActiveProfiles(ApplicationConstants.DEVELOPMENT\u配置文件)
@WebAppConfiguration
公共类EmployeeServiceTest{
@注射模拟
员工服务员工服务;
@嘲弄
雇员职位雇员职位;
字符串名;
@以前
公共void init(){
initMocks(this);
}
@试验
公众雇员(){
Mockito.when(employeeRepository.findByName(name)).thenReturn(getEmployee());
List resultedEmployees=employeeService.getEmployeeByName(“mike”);
}
私有列表getEmployee(){
//下面是返回列表的逻辑
}
}
公共EmployeeServiceImpl实现EmployeeService{
@自动连线
雇员职位雇员职位;
雇员服务。
公共列表getEmployeeByName(字符串名称){
List employeeRepository.findByName(姓名);
//在这里,我不想访问真实的数据库,所以我在testcase中模拟了它,但在调试它时,我得到了一个空列表。所以,您能告诉我,我在“EmployeeServiceTest”中获取列表时做错了什么吗
}
}
因此,在testcase中是否需要任何额外的逻辑来获取模拟对象。问题在于您没有模拟调用
employeeRepository.findByName("mike")
但你在嘲笑我
employeeRepository.findByName(null)
因为变量name
从未初始化。将代码更改为:
Mockito.when(employeeRepository.findByName("mike")).thenReturn(getEmployee());
是声明
字符串名称代码>在你的测试中真的是这样,还是复制粘贴错误?是的,我声明了字符串名;真的在我的员工服务测试中。这不是抄袭过去。