spring 集成 junit
dwd4
10年前
spring 集成 junit,方便测试,特别是使用TTD方法开发。
1、spring是纯java方式配置,集成junit如下:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.redis.demo.init.AppConfig; /** * 共用 dao * * @author sean * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AppConfig.class }) public class BaseDaoTest { @Test public void _() { } }
2、spring是xml文件的方式配置,集成junit如下:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 共用 dao * * @author sean * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:applicationContext.xml"}) public class BaseDaoTest { @Test public void _() { } }
这样其他的测试类就可以继承这个BaseDaoTest,这样我们的测试就相当方便。举例如下
import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.redis.demo.core.entity.Member; public class MemberDaoTest extends BaseDaoTest { @Autowired private IMemberDao memberDao; private Member member; @Before public void setUp() { member = new Member(); member.setName("魏升水"); member.setCardNum("25215411200"); } /** * 测试保存会员 */ @Test public void testSaveMember() { saveMember(member); Assert.assertNotNull(member.getId()); memberDao.saveMember(member); Assert.assertNotNull(member.getId()); } /** * 测试通过id查询会员 */ @Test public void testGetMemberById() { // 添加数据 saveMember(member); // case 1: id 存在,能查询到数据 String id = member.getId(); Member member2 = memberDao.getMemberById(id); Assert.assertEquals(member.getId(), member2.getId()); // case 2: id 不存在,不能查询到数据 id = id + "1"; Member member3 = memberDao.getMemberById(id); Assert.assertNull(member3); } /** * 查询所有会员 */ @Test public void testGetAllMembers() { // 前置检查:现在还没有添加数据,一个会员也没有 List<Member> members = memberDao.getAllMembers(); Assert.assertEquals(0, members.size()); // 添加数据: 保存两个会员 // save member1 saveMember(member); // save member2 member = new Member(); member.setName("jredis"); member.setCardNum("20150324"); saveMember(member); members = memberDao.getAllMembers(); Assert.assertEquals(2, members.size()); } /** * 测试根据id删除会员 */ @Test public void testDeleteMemberById() { // 数据准备 saveMember(member); // case 1: 指定的id存在,删除成功 String id = member.getId(); boolean isDeleted = memberDao.deleteMemberById(id); Assert.assertTrue(isDeleted); // case 2: 指定的id不存在,删除失败 id = id + "1"; isDeleted = memberDao.deleteMemberById(id); Assert.assertFalse(isDeleted); } private void saveMember(Member member) { memberDao.saveMember(member); } }