我想InjectMocks
进入我的界面,而不是我的服务类,到目前为止,Mockito无法实现(我使用的是Mockito 2.8.9)。我使用过SpringBoot并使用@MockBean
我能够测试服务的接口,但是使用Spring @Mock
的SpringMvc,我只能测试一个具体的类,为什么以及我该怎么做才能测试服务?
有关如何将其设置为接口级别的任何建议。
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = EmployeeServiceImpl.class)
public class EmployeeServiceTest {
@org.mockito.Mock
private EmployeeDao employeeDao;
@InjectMocks
private EmployeeServiceImpl employeeService ;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void SaveEmployee() throws Exception {
Employee employee = new Employee();
employee.setEmployeeName("valentine");
employee.setSalary(400);
employee.setDepartmentId(1);
employee.setEmployeeId(1);
Employee employee1 ;
when(employeeDao.addEmployee(employee)).thenReturn(employee);
employee1 = employeeService.saveEmployee(employee);
org.junit.Assert.assertNotNull(employee);
assertEquals(employee1.getSalary(), employee.getSalary());
Mockito.verify(employeeDao).addEmployee(employee);
}
答案 0 :(得分:3)
所以我首先在Config类中创建了Bean,它返回了Dao的接口
@Profile("test")
@Configuration
public class Config {
@Bean
@Primary
public EmployeeDao employeeDao(){
return Mockito.mock(EmployeeDao.class);
}
}
然后我在测试中使用了配置文件,并将configContxt设置为我的配置类
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes ={ EmployeeServiceImpl.class, Config.class})
public class EmployeeServiceTest1 {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private EmployeeService employeeService;