阅读更多
//首先创建一个接口BaseDao.java
package com.abin.lee.easymock;
/**
* Created with IntelliJ IDEA.
* User: abin
* Date: 13-4-22
* Time: 上午8:06
* To change this template use File | Settings | File Templates.
*/
public interface BaseDao {
public String queryById(String id);
}
//创建一个调用类BaseService.java
package com.abin.lee.easymock;
/**
* Created with IntelliJ IDEA.
* User: abin
* Date: 13-4-22
* Time: 上午8:09
* To change this template use File | Settings | File Templates.
*/
public class BaseService {
private BaseDao baseDao;
public void setDao(BaseDao baseDao){
this.baseDao=baseDao;
}
public String carryQuery(String id){
return this.baseDao.queryById(id);
}
}
//创建一个测试类:BaseTest.java
package com.abin.lee.easymock;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: abin
* Date: 13-4-22
* Time: 上午8:12
* To change this template use File | Settings | File Templates.
*/
public class BaseTest {
@Test
public void testBaseDao(){
//1、创建mock对象,以接口形式创建
BaseDao baseDaoMock= EasyMock.createMock(BaseDao.class);
//2、设定参预期和返回,查询预期值得到所设定的预期结果
EasyMock.expect(baseDaoMock.queryById("111")).andReturn("abin");
//3、结束录制
EasyMock.replay(baseDaoMock);
//比较service调用的值是否与设定的值相同
BaseService baseService=new BaseService();
baseService.setDao(baseDaoMock);
String result=baseService.carryQuery("111");
System.out.println("result="+result);
TestCase.assertNotNull(result);
TestCase.assertEquals("abin",result);
//4、回放录制
EasyMock.verify(baseDaoMock);
}
}