JMock相关

上一篇 / 下一篇  2014-11-04 22:06:07 / 个人分类:单元测试

JMock简介
JMock是写单元测试时需要生成mock对象时很好的辅助库。
 
将jmock-2.5.1.jar和jmock-junit4-2.5.1.jar添加到工程的classpath。
 
//表示使用JMock运行测试用例
 
@RunWith(JMock.class)
public class JMockTest {
 
}
Mock对象上下文:Mockery类代表着所测试对象与之交互的测试环境.
      //模拟接口
      Mockery context = new JUnit4Mockery();
 
      //如果模拟类,使用如下上下文
       Mockery context = new Mockery() {
    //模拟类
    {setImposteriser(ClassImposteriser.INSTANCE);}
};
 
模拟对象:
      final UserDao userDao = context.mock(UserDao.class);
根据期望值测试(Tests with Expectations)
@Test
public void testCreateSuccess() {
 
context.checking(new Expectations() {
{   
       //one表示一次调用,with(any(String))表示可以有任何String参数
one(userDao).create(with(any(String.class)));
//will(returnValue(true)) 表示调用将返回true
will(returnValue(true));
}
});
Assert.assertTrue(userDao.create("z"));
}
注意:这里有一个很令人郁闷的语法。{{,仔细听老师讲述。
invocation-count(mock-object).method(argument-constraints);   
inSequence(sequence-name);
when(state-machine.is(state-name));
will(action);
then(state-machine.is(new-state-name));
 
invocation-count 调用的次数约束
mock-object mock对象
method 方法
argument-constraints 参数约束
inSequence 顺序
when mockery的状态机
will(action) 方法触发的动作
then 方法触发后设置mockery的状态
//具体相等
allowing(dao).sayHello("ok");
//具体相等
allowing(dao).sayHello(with(equal("ok")));
//字符串包含
allowing(dao).sayHello(with(new StringContains("ok")));
//==判断
allowing(dao).sayHello(with(same("ok")));
//String类型的null
allowing(dao).sayHello(with(aNull(String.class)));
//String类型,但是不是null
allowing(dao).sayHello(with(aNonNull(String.class)));
//String类型的任何东西,可以包含null
allowing(dao).sayHello(with(any(String.class)));
返回值:oneOf (anObject).doSomething(); will(returnValue(10));
      在连续调用中返回不同值  :
oneOf (anObject).doSomething(); will(returnValue(10));
oneOf (anObject).doSomething(); will(returnValue(20));
oneOf (anObject).doSomething(); will(returnValue(30));
第一次调用 doSomething 会返回 10,第二次返回 20,第三次返回30.
      从模拟方法抛出异常:
allowing (bank).withdraw(with(any(Money.class)));    will(throwException(new WithdrawalLimitReachedException());
      不同参数值返回不同结果
allowing (calculator).add(1,1); will(returnValue(3));
allowing (calculator).add(2,2); will(returnValue(5));
allowing (calculator).sqrt(-1); will(throwException(new Exception());

TAG:

 

评分:0

我来说两句

Open Toolbar