mock是个轻量级的单元测试框架,做单元测试优点特别多,下边先来一段比较简单的实例
首先maven依赖的包有:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
</dependency>
以及其他单元测试包
@Service
public class HelloServiceImpl implements HelloService {
@Autowired
private HelloDao testqDao;
@Override
public Integer selectCount() {
Integer count=testqDao.selectCount();
return count;
}
}
比如我们测试HelloService类,他的实现类testqDao.selectCount()这个方法会去查数据库,那怎么让他不去查数据库,而是执行到这里的时候返回一段咱们模拟的数据呢?⏬
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-application-context.xml")
public class HelloServiceTest {
@InjectMocks
@Autowired
private HelloService helloService; //注入service
@Mock
private HelloDao helloDao; //模拟dao
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this); //初始化mock
}
/**
* 测试记录条数
*
* @throws Exception
*/
@Test
public void selectCount() throws Exception {
Integer count = 5;
when(helloDao.selectCount()).thenReturn(5);//when(something.do). thenReturn(模拟返回的值)
Integer total = helloService.selectCount();
System.out.println("total=" + total);
Assert.assertEquals(count, total);//断言返回的数据是5,这里我数据库是只有两条数据的,返回5,即就是断言成功时,咱们拿到的就是模拟到的数据,而并不是真正数据库里数据
}
}
mock还有很多东西,这只是一个很简单的例子,更多资料后续更新,下边附上测试图片