二、编写SpringJunit(依赖包:spring-test-3.0.4.RELEASE.jar,junit4,以及其他的spring核心包),还是以User为例子,我们编写UserTestUnit来验证我们后台的方法,如下:
/** * @author fisher * @description 用户业务测试 */ // 使用springJunit4 @RunWith(SpringJUnit4ClassRunner.class) // spring配置文件加载(locations为文件路径) @ContextConfiguration(locations = { "classpath:spring/application-hibernate.xml", "classpath:spring/application-common-service.xml", "classpath:spring/application-sys-service.xml" }) public class UserTestJunit { @Autowired UserService userService;// 自动注入userService /** * @description 测试查询用户 * @throws Exception */ @Test public void query() throws Exception { List result = userService.getAllEmployee(); Assert.notEmpty(result); } /** * @description 测试用户添加 * @throws Exception */ @Test public void save() throws Exception { User user = new User(); user.setUsrCode("test001"); user.setUsrName("test"); user.setPassword("123"); user.setIdCard("513029198503140026"); user.setEmail("aaa@sina.com"); User u = userService.save(user); Assert.notNull(u); org.junit.Assert.assertEquals("test", user.getUsrName()); } /** * @description 测试用户更新 * @throws Exception */ @Test public void update() throws Exception { User user = new User(); user.setUsrCode("test001"); user.setUsrName("test"); user.setPassword("123"); user.setIdCard("513029198503140026"); user.setEmail("aaa@sina.com"); User u = userService.update(user); Assert.notNull(u); org.junit.Assert.assertEquals("test", user.getUsrName()); } /** * @description 测试用户删除 * @throws Exception */ @Test public void del() throws Exception { User user = new User(); user.setUserId("1"); User u = userService.delete(user); Assert.notNull(u); org.junit.Assert.assertEquals("1", user.getUserId()); } } |
【总结】单元测试不仅限于此,灵活性比较大,要结合实际进行编写,上面两种测试是按照我们项目中规范编写,大家可以作为参考,自我觉得还是比较实用而且用注解方式比较方便。