Java Spring MVC 4服务@tTransactional不';行不通
Java Spring MVC 4服务@tTransactional不';行不通,java,spring,spring-mvc,Java,Spring,Spring Mvc,1。Spring MVC应用程序上下文.xml <tx:annotation-driven/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username
1。Spring MVC应用程序上下文.xml
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="test"/>
<property name="password" value="test"/>
<property name="url" value="jdbc:mysql://localhost:13306/test"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
3。测试用例
@Test
public void rollbackT() {
boolean hasException = false;
int sizeBeforDelete = commentDAO.selectCountByArticle(1);
try {
commentService.deleteCommentAndFiles(1);
} catch (RuntimeException e) {
hasException = true;
}
Assert.assertTrue(hasException);
Assert.assertEquals(sizeBeforDelete, commentDAO.selectCountByArticle(1));
}
在测试用例中
首先Assert.assertTrue(hasException)代码>已传递,但
Assert.assertEquals(sizeBeforDelete,commentDAO.selectCountByArticle(1))
此案例失败预期为1,实际为0
第二次TC失败意味着发生异常,但不会回滚删除注释
deleteComentandFiles方法
抛出异常但不回滚
我试图使用@Transactional(propagation=propagation.REQUIRED,rollboor={incorrectionpdatesemanticsdataaccessexception.class})
但同样的方法是行不通的
为什么@Transactional注释不起作用?数据库必须支持事务。对于MySQL,您需要创建一个InnoDB、BDB或Genini类型的表
默认情况下,myisam不支持事务 我没有看到您的主测试类,但我假设您使用junit的默认spring配置:
默认情况下,对他自己的隐式事务启动测试。当您调用服务时,它会启动一个“子”逻辑事务(这是测试事务的一部分,因为您没有使用require_new进行传播)。当该事务失败时,主事务被标记为回滚,但回滚直到主事务完成(测试结束时)才完成
如果要测试回滚,则不应使用此由测试框架启动的隐式事务,也可以在断言之前使用TestTransaction.end()
强制提交或回滚此事务。我也遇到了同样的问题。我将@transactional移动到控制器以使其工作
@启用TransactionManagement并仅在定义它们的相同应用程序上下文中查找bean上的@Transactional。这意味着,如果在DispatcherServlet的WebApplicationContext中放置注释驱动配置,它只检查控制器中的@Transactional bean,而不检查服务。有关更多信息,请参见第21.2节“DispatcherServlet”
表引擎是innoDB
,所以不能只进行单元测试就测试回滚吗?什么是测试框架
?没有主测试类
,因为我只想测试deleteCommentAndFiles
方法:(我说的是您测试的类。使用@RunWith(SpringJUnit4ClassRunner.class)的带有spring注释和junit runnerim的类)
@WebAppConfiguration
@ContextConfiguration
@Test
public void rollbackT() {
boolean hasException = false;
int sizeBeforDelete = commentDAO.selectCountByArticle(1);
try {
commentService.deleteCommentAndFiles(1);
} catch (RuntimeException e) {
hasException = true;
}
Assert.assertTrue(hasException);
Assert.assertEquals(sizeBeforDelete, commentDAO.selectCountByArticle(1));
}