我想InjectMocks
我的界面而不是我的服务类,到目前为止,Mockito是不可能的(我使用的是Mockito 2.8.9(。我使用过SpringBoot,使用@MockBean
我能够测试服务的接口,但是使用SpringMvc @Mock
,我只能测试一个具体的类,为什么以及我可以做些什么来测试服务?
关于如何将其提升到界面级别的任何建议。
@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);
}
所以我首先在返回 Dao 接口的 Config 类中创建 Bean 来解决这个问题
@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;