如何上手EasyMock?

在Eclipse上创建Project, MockTest

创建Interface

  1. public interface IStudent {  
  2.     public String doMethod1();  
  3.     public String doMethod2();  
  4.     public String doMethod3();  
  5.   
  6. }  
创建被测类

  1. public class StudentApplication {  
  2.     IStudent student=null;  
  3.     public StudentApplication(IStudent student) {  
  4.         this.student = student;  
  5.     }  
  6.       
  7.     public String doMethod(){  
  8.         String str1=student.doMethod1();  
  9.         String str2=student.doMethod2();  
  10.         String str3=student.doMethod3();  
  11.         return str1+str2+str3;  
  12.     }  
  13. }  
在Eclipse里右键点击 StudentApplication.java,点New,选JUnit Test Case

同意导入JUnit4库

下载Easy Mock

https://sourceforge.net/projects/easymock/?source=typ_redirect


右键选择项目,点属性,Java Build Path -> Libraries ->Add External Jar, 找到解压后的easymock-3.2.jar


修改StudentApplicationTest.java如下。

  1. import main.IStudent;  
  2. import main.StudentApplication;  
  3. import org.easymock.EasyMock;  
  4. import org.junit.Assert;  
  5. import org.junit.Test;  

  6.   
  7. public class StudentApplicationTest {  
  8.     IStudent student;  
  9.     StudentApplication application;  
  10.     @Test  
  11.     public void testdoMethod(){  
  12.         //•使用 EasyMock 生成 Mock 对象;  
  13.         student=EasyMock.createMock(IStudent.class);  
  14.         //设定 Mock 对象的预期行为和输出  
  15.         EasyMock.expect(student.doMethod1()).andReturn("a").times(1);  
  16.         EasyMock.expect(student.doMethod2()).andReturn("b").times(1);  
  17.         EasyMock.expect(student.doMethod3()).andReturn("c").times(1);  
  18.         //将 Mock 对象切换到 Replay 状态  
  19.         EasyMock.replay(student);  
  20.         //调用 Mock 对象方法进行单元测试  
  21.         application=new StudentApplication(student);  
  22.         String getStr=application.doMethod();  
  23.         //对 Mock 对象的行为进行验证  
  24.         String cstr="abc";//正确的字符串  
  25.         Assert.assertEquals(cstr,getStr);  
  26.         EasyMock.verify(student);  
  27.           
  28.     }  
  29. }  

右键点击StudentApplicationTest.java,Run As -> JUnit Test


注:以上代码来自网络,有少许修改。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值