EasyMock提供了一個功能,用以模擬丟擲異常,所以例外處理可以進行測試。
//add the behavior to throw exception EasyMock.expect(calcService.add(10.0,20.0)).andThrow(new RuntimeException("Add operation not implemented"));
在這裡,我們新增了一個異常子句模仿物件。 MathApplication利用使用calcService其Add方法和模型將丟擲RuntimeException異常時呼叫calcService.add()方法。
建立一個介面CalculatorService,其目的是提供各種計算相關的功能。
CalculatorService.javapublic interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); }
建立一個Java類用來表示MathApplication。
MathApplication.javapublic class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } }
讓我們來測試MathApplication類,通過它注入CalculatorService作一個模擬。Mock將由EasyMock建立。
MathApplicationTester.javaimport org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; //@RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { //@TestSubject annotation is used to identify class which is going to use the //mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test(expected = RuntimeException.class) public void testAdd(){ //add the behavior to throw exception EasyMock.expect(calcService.add(10.0,20.0)).andThrow(new RuntimeException("Add operation not implemented")); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } }
建立一個Java類在檔案夾 C:\ > EasyMock_WORKSPACE 執行測試用例
TestRunner.javaimport org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
使用javac編譯如下類
C:\EasyMock_WORKSPACE>javac MathApplicationTester.java
現在執行測試執行看結果
C:\EasyMock_WORKSPACE>java TestRunner
驗證輸出
true