在上面篇文章,我们的测试代码如下:
1package com.martin.pdo;
2
3import org.springframework.context.ApplicationContext;
4
5import junit.framework.Assert;
6import junit.framework.TestCase;
7
8public class UserTest extends TestCase {
9
10 public void testUser() {
11 ApplicationContext context = JUnitTestHelper.getContext();
12 User user = (User) context.getBean("user");
13 User _u1 = new User();
14 _u1.setName("martin xus");
15 _u1.setSex('F');
16 _u1.setAge(100);
17 user.add(_u1);
18
19 Assert.assertNotNull(_u1.getId());
20
21 User _u2 = (User) user.loadByName("martin xus").get(0);
22 Assert.assertEquals(_u1.getId(), _u2.getId());
23
24 user.remove(_u2);
25 Assert.assertTrue(user.loadByName("martin xus").size() == 0);
26 }
27
28}
29
而这些,必须要和spring&hibernate一起工作,必须保证数据库操作正确,而我们需要的只是测试这个类的本身!
有必要连hibernate,spring一起测试吗?当然没有,测试,只需要保证本代码完成相应的功能,即可.
那么就有必要更换测试方法:
mock便是首选,在这里我们选择了jmock (http://www.jmock.org)
1package com.martin.mock;
2
3import org.jmock.Mock;
4import org.jmock.MockObjectTestCase;
5
6import java.util.List;
7
8/** *//**
9 * @author martin.xus
10 */
11public class UserTest extends MockObjectTestCase {
12
13 public void testAdd() {
14 Mock mock = mock(UserManager.class);
15 User user = new User();
16 mock.expects(once()).method("add").with(isA(User.class));
17 UserManager manager = (UserManager) mock.proxy();
18
19 user.setManager(manager);
20 user.add(new User());
21 mock.verify();
22 }
23
24 public void testLoadByName() {
25 Mock mock = mock(UserManager.class);
26 User user = new User();
27
28 mock.expects(once()).method("loadByName").with(isA(String.class)).will(returnValue(List.class));
29 UserManager manager = (UserManager) mock.proxy();
30
31 user.setManager(manager);
32 user.loadByName("martin");
33 mock.verify();
34 }
35
36 public void testRemove(){
37 Mock mock = mock(UserManager.class);
38 User user = new User();
39
40 mock.expects(once()).method("remove").with(isA(User.class));
41 UserManager manager = (UserManager) mock.proxy();
42
43 user.setManager(manager);
44 user.remove(user);
45 mock.verify();
46 }
47}
ok,测试通过