转载请注明:来自http://blog.csdn.net/M_ChangGong/ 作者:张燕广
该篇主要编写修改配置文件完成最后的整合工作,并编写单元测试代码,对整合后的代码进行单元测试。
在applicationContext.xml文件中配置service和DAO层bean,在配置文件中添加的配置代码如下:
<bean id="studentDao" class="com.zyg.ssj.dao.jpa.StudentDaoImpl"/> <bean id="studentService" class="com.zyg.ssj.service.impl.StudentServiceImpl"/>
至此,完成了全部整合工作,下面我们创建junit单元测试类:
在src下创建包com.zyg.ssj.junit.test,在该包下创建基于junit4的测试类StudentServiceTest,类文件代码如下:
package com.zyg.ssj.junit.test; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zyg.ssj.bean.Student; import com.zyg.ssj.service.StudentService; public class StudentServiceTest { private static StudentService studentService; @BeforeClass public static void setUpBeforeClass() throws Exception { try { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); studentService = (StudentService)ctx.getBean("studentService"); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testSave() { studentService.save(new Student("changong")); } @Test public void testUpdate() { Student s = studentService.getStudent(1); s.setStuName("chang"); studentService.update(s); } @Test public void testGetStudent() { Student s = studentService.getStudent(1); System.out.println(s.getStuName()); } @Test public void testGetStudents() { List<Student> students = studentService.getStudents(); for(Student s : students){ System.out.println(s.getStuName()); } } @Test public void testDelete() { try { studentService.delete(1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行方法testSave,结果并不是我们想象的那样,出现了异常!!!
不要紧张,我们仔细观察一下控制器的错误信息,在错误信息的最后一部分我们发现如下信息:
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
什么意思呢?我们还没加入mysql的驱动包吧??!!
在实际项目开发中我们应该一次性加入全部jar包。
在lib目录下加入mysql-connector-java-3.1.11-bin.jar,刷新一下项目,再次执行testSave方法,OK,一切搞定。
至此,Spring2.5整合jpa的代码全部完成,从下一篇开始我们逐步把struts1.3.8整合到我们的项目中。