//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);
}
}