spring version 3.1
首先搭建环境 本开发环境为spring3.1+springmvc+hibernate3+mysql5
与开发环境所不同的一点是 在XmlWebApplicationContext的配置文件([servlet-name]-servlet.xml)中需要加入AnnotationMethodHandlerAdapter的定义。
由于本测试用到了事务,因此在applicationContext.xml中需要加入transactionManager的定义。
配置文件mvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mvc.controller"/>
<bean id="adapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
</beans>
配置文件applicationContext.xml中的transactionManager:
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
实现Controller,UserController:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/register.do")
public String register(HttpServletRequest req, String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
this.userService.save(user);
return "success";
}
}
实现测试类, UserControllerTest:
@RunWith(SpringJUnit4ClassRunner.class) //使用JUnit4测试框架
@ContextConfiguration(locations={"classpath:applicationContext.xml", "classpath:mvc-servlet.xml"}) //指定context的配置文件路径
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true) //Transaction的配置,context中必须有一个可用的transactionManager
public class UserControllerTest {
@Autowired
private UserController userController;
@Autowired
private AnnotationMethodHandlerAdapter adapter;
@Test
@Transactional //指定了该方法在事务中执行
public void register() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse resp = new MockHttpServletResponse();
req.setRequestURI("/register.do");
req.setParameter("name", "zhangsan");
req.setParameter("password", "123456");
ModelAndView mv = adapter.handle(req, resp, userController);
Assert.assertEquals("success", mv.getViewName());
}
}
测试结果: 数据库中没有数据插入