Java开发过程中需要使用EasyMock做单元测试,上手使用了一下,记录之!
  开发环境:
  JDK7.0+MyEclipse10+EasyMock3.3.1+Win7+JUnit4
1) 接口IAlgorithm.java
package com.wicresoft.EKA;
public interface IAlgorithm {
public int Add(int x,int y);
public int Mul(int x,int y);
}
2) 实现接口
package com.wicresoft.EKA;
public class Algorithm implements IAlgorithm {
public int Add(int x,int y){
return x + y;
}
public int Mul(int x,int y){
return x * y;
}
}
3) 调用者
package com.wicresoft.EKA;
public class Calcutor {
private IAlgorithm agent;
public Calcutor(IAlgorithm agent){
this.agent = agent;
}
public int CalcAdd(int x,int y){
return agent.Add(x, y);
}
}
4) 单元测试
package com.wicresoft.EKA.Test;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.junit.Test;
import com.wicresoft.EKA.*;
public class AlgorithmTest extends EasyMockSupport {
@Test
public void testAdd() {
Algorithm algorithm = new Algorithm();
int expected = 10;
int actual = algorithm.Add(3, 7);
assertEquals(expected, actual);
}
@Test
public void testMul() {
try{
int x = 3;
int y = 4;
int z = 7;
IAlgorithm mock = createMock(IAlgorithm.class);
Calcutor calc = new Calcutor(mock);
EasyMock.expect(calc.CalcAdd(x,y)).andReturn(z).anyTimes();
EasyMock.replay(mock);
EasyMock.verify(mock);
}catch(Exception e){
e.printStackTrace();
}
}
}