少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
//UserDao.java

package com.abin.lee.jmock;

/**
 * Created with IntelliJ IDEA.
 * User: abin
 * Date: 13-4-23
 * Time: 上午11:07
 * To change this template use File | Settings | File Templates.
 */
public interface UserDao {
    public String getMessage(String message);
}





//UserService.java

package com.abin.lee.jmock;

/**
 * Created with IntelliJ IDEA.
 * User: abin
 * Date: 13-4-23
 * Time: 上午11:06
 * To change this template use File | Settings | File Templates.
 */
public class UserService {
   private UserDao userDao;

   public String findMessage(String message){
       return this.userDao.getMessage(message);
   }

    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
}





//UserManageTest.java

package com.abin.lee.jmock;

import junit.framework.TestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;

/**
 * Created with IntelliJ IDEA.
 * User: abin
 * Date: 13-4-23
 * Time: 上午11:08
 * To change this template use File | Settings | File Templates.
 */
public class UserManageTest {
    @Test
    public void testUserManage(){
        // 建立一个test上下文对象。
        Mockery mockery=new Mockery();
        // 生成一个mock对象
        final UserDao userDao=mockery.mock(UserDao.class);
        // 设置期望。
        mockery.checking(new Expectations(){
                {
                    // 当参数为"abin"的时候,userDao对象的getMessage方法被调用一次,并且返回西安。
                    oneOf(userDao).getMessage("abin");
                    will(returnValue("abin"));
                }
        });
        UserService userService=new UserService();
        userService.setUserDao(userDao);
        String message=userService.findMessage("abin");
        System.out.println("message="+message);
        TestCase.assertEquals("abin",message);

    }
}

posted on 2013-04-23 11:29 abin 阅读(575) 评论(0)  编辑  收藏 所属分类: JMOCK

只有注册用户登录后才能发表评论。


网站导航: