EasyMock第一應用程序

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.java

public 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.java

public 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.java

import 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.java

import 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