到目前為止,我們已經(jīng)使用注解來創(chuàng)建Mocks。 EasyMock提供了各種方法來創(chuàng)建模擬對象。 EasyMock.createMock()創(chuàng)建的模擬,但沒有理會方法的順序調(diào)用模擬會在作出其行動的適當(dāng)時機(jī)。
calcService = EasyMock.createMock(CalculatorService.class);
創(chuàng)建一個接口CalculatorService,其目的是提供各種計算相關(guān)的功能。
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); }
創(chuàng)建一個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創(chuàng)建。
在這里,我們已經(jīng)添加了兩個模擬方法調(diào)用,add()和subtract()來模擬對象,通過expect()。但在測試過程中,我們調(diào)用Add()方法前調(diào)用subtract()。當(dāng)我們創(chuàng)建模擬對象使用EasyMock.createMock(),以便執(zhí)行方法。
MathApplicationTester.javaimport org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EasyMockRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = EasyMock.createMock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAddAndSubstract(){ //add the behavior to add numbers EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0); //subtract the behavior to subtract numbers EasyMock.expect(calcService.subtract(20.0,上一篇:EasyMock calcService.serviceUsed()調(diào)用兩次示例下一篇:EasyMock times(min,max)示例