菜鸟学习Jmock测试-入门(二)

第一个实例:

建立一个testcase的步骤:

1、建立一个test上下文对象

2、生成一个mock对象  

3、设置期望

4、设置mock对象

5、调用方法

6、验证返回值

实例(用户服务测试):测试用户服务中根据userId查询用户表中某个业务(本例子中采用的是鲜花)的未读数。

public class UserServiceTest extends AbstractTest{
@Autowired
UserService userService;  //声明用户服务 
@Test
public void test() throws InterruptedException{
// 建立一个test上下文对象。   
    Mockery context = new  Mockery();
// 生成一个mock对象   
   final  MsgFlowerDao msgFlowerDao = context.mock(MsgFlowerDao.class );     
// 设置期望
   context.checking(new  Expectations() {  
       {  
           // 当userId = 1的时候,msgFlowerDao对象的getCountByUserIdAndTime方法被调用,并且返回值为3。   
            Date addTime = Calendar.getInstance().getTime();
        allowing(msgFlowerDao).getCountByUserIdAndTime(1, addTime);  
           will(returnValue(3));  
        }  
 });
int result = flowerService.getUnreadCountByUserId(1);
equal(result,3);
}
}

你可能感兴趣的:(jmock测试)