EasyMock的使用


1.Mock 方法是單元測試中常見的一種技術,它的主要作用是模擬一些在應用中不容易構造或者比較復雜的對象,從而把測試與測試邊界以外的對象隔離開。同時也可以當調用別人的模塊,而該模塊又沒有實現時(只提供接口),我們可以在獨立的環境中測試自己的模塊邏輯。

2.使用前的准備,下載所需的jar包:easymock-3.0.jar(或以上版本),junit-4.4.jar,cglib-nodep-2.1_3.jar

3.使用方法較簡單。主要有以下步驟:

 *•使用 EasyMock 生成 Mock 對象;
 *•設定 Mock 對象的預期行為和輸出;
 *•將 Mock 對象切換到 Replay 狀態;
 *•調用 Mock 對象方法進行單元測試;
 *•對 Mock 對象的行為進行驗證。

測試實例:假如我有一個IStudent接口類和StudentApplication類,StudentApplication類中用到了IStudent中的沒實現的方法,而我想測試StudentApplication,這時用EasyMock構造一個IStudent的Mock對象,並給要用到的的未實現的方法設定已知返回值。

code:

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(){
4
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
14 public IStudent getStudent() {
15 return student;
16 }
17
18 public void setStudent(IStudent student) {
19 this.student = student;
20 }
21
22
23
24 }
 1 import main.IStudent;
2 import main.StudentApplication;
3
4 import org.easymock.EasyMock;
5 import org.junit.Assert;
6 import org.junit.Test;
7
8
9 public class testStudentApplication {
10 IStudent student;
11 StudentApplication application;
12 @Test
13 public void testdoMethod(){
14 //•使用 EasyMock 生成 Mock 對象;
15 student=EasyMock.createMock(IStudent.class);
16 //設定 Mock 對象的預期行為和輸出
17 EasyMock.expect(student.doMethod1()).andReturn("a").times(1);
18 EasyMock.expect(student.doMethod2()).andReturn("b").times(1);
19 EasyMock.expect(student.doMethod3()).andReturn("c").times(1);
20 //將 Mock 對象切換到 Replay 狀態
21 EasyMock.replay(student);
22 //調用 Mock 對象方法進行單元測試
23 application=new StudentApplication();
24 application.setStudent(student);
25 String getStr=application.doMethod();
26 //對 Mock 對象的行為進行驗證
27 String cstr="abc";//正確的字符串
28 Assert.assertEquals(getStr, cstr);
29 EasyMock.verify(student);
30
31 }
32
33 }



----點點滴滴,天地之間-----

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM