EasyMock学习

初步研究了下easymock,现在把测试代码和心得共享下。

先介绍下easymock。

EasyMock是一种模拟测试的框架,用他来辅助模拟测试。当在测试过程中一些复杂的对象生成相当麻烦、费时或者根本无法生成时,可以用模拟的对象来代替真实的对象。

举例说,现在你要测试一个类的方法,但这个方法里面又要调用其他对象的方法,而这些方法还没写或者比较难实现。这时你就可以用easymock来解决。

测试代码:

接口,还没写好的方法。

public interface IStudent {
public String doMethod1();
public String doMethod2();
public String doMethod3();
}

主要关注的类,要测试的方法需要用到之前没写好的方法

public class StudentApplication {
IStudent student=null;
public StudentApplication(){


}
public String doMethod(){
String str1=student.doMethod1();
String str2=student.doMethod2();
String str3=student.doMethod3();
return str1+str2+str3;

}
public IStudent getStudent() {
return student;
}
public void setStudent(IStudent student) {
this.student = student;
}
}

junit4 测试用例

import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.Test;
public class StudentApplicationTest {
private IStudent student;
private StudentApplication application;

//基本测试
@Test
public void testdoMethod(){
//在record阶段,这里我们开始创建mock对象,并期望这个mock对象的方法被调用,同时给出我们希望这个方法返回的结果
student=EasyMock.createMock(IStudent.class);
EasyMock.expect(student.doMethod1()).andReturn("1");
EasyMock.expect(student.doMethod2()).andReturn("2");
EasyMock.expect(student.doMethod3()).andReturn("3");

//在replay阶段,我们关注的主要测试对象将被创建,之前在record阶段创建的相关依赖被关联到主要测试对
//象,然后执行被测试的方法,以模拟真实运行环境下主要测试对象的行为。
EasyMock.replay(student);
application=new StudentApplication();
application.setStudent(student);
String str=application.doMethod();

//在verify阶段,我们将验证测试的结果和交互行为
String expectedStr="123";
assertEquals(expectedStr, str);
EasyMock.verify(student);
}


工程除了要导入easymock-3.0.jar,junit4的包外,还需要导入cglib-nodep-2.1_3.jar这个包。不然会报错。

这个就是easymock最基本的使用了。当然还有很多知识点,就不多做说明了。

原文地址:https://www.cnblogs.com/yuxiaorong/p/2268670.html