- 浏览: 52598 次
- 性别:
- 来自: 北京
-
文章分类
最新评论
-
xing_yeli:
谢谢大神!!
Action[/***] does not contain specified method (check logs) -
peng860226327:
...
JUnit 3.8.2和JUnit 4.8.1学习笔记 -
jiangli15:
写的真心的好!!
Spring 3.0 + Struts 2.1 + Hibernate 3.3 框架整合小结 -
清子123杨:
写得很清楚,多谢作者了
Spring 3.0 + Struts 2.1 + Hibernate 3.3 框架整合小结 -
zuoshou19w:
lynn.ge 写道
Spring 3.0 + Struts 2.1 + Hibernate 3.3 框架整合小结
SSH+Log4j+JUnit+MySql整合Web Project练习小结,重点在Spring上如何进行JUnit测试
前3天都是单独小练习,今天做一个整合小练习,看看会不会出现一些问题。。。
例子很简单,Spring 3 + Struts 2 + Hibernate 3 + Log4j 1.2.14 + Junit 4.8.1 + MySql 5.5
基于上述技术实现一个超简单的Web Project 功能就是CRUD。。。(登录+管理)。。。go go go。。。
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
文中只列出一些在操作中要注意的事项,和遇到的问题而已。
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
这次把Spring的配置文件applicationContext.xml放在了src下。
(其实,平时习惯放在WEB-INF下,但在JUnit测试的时候我自己找不对路径,所以放src下用classpath来设置了)
当然,放在src下,就要在Web.xml中配置路径参数:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
JUnit:
针对用户业务层的 UserinfoBizImp 类做了测试,如下UserinfoBizImplTest:
这里会用到Spring框架中的一个test架包,是我在练习时单独添加的,末段提供下载。
其他jar包基本都是MyEclipse提供的,。
package com.mysqlweb.biz.impl; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mysqlweb.biz.UserinfoBiz; import com.mysqlweb.entity.Userinfo; /** * * @author Maxpin on 2011-10-04 * * UserinfoBizImpl测试类 */ @RunWith(SpringJUnit4ClassRunner.class)//org.springframework.test.context.junit4.SpringJUnit4ClassRunner @ContextConfiguration(locations={"classpath:applicationContext.xml"}) //配置Spring配置文件路径 public class UserinfoBizImplTest { @Autowired //自动装配注入 UserinfoBiz userBiz; @Test public void testLogin(){ //测试登录 userBiz.login("admin", "123123"); } @Test public void testQueryUserinfoById(){ //测试查询单个 Userinfo user = userBiz.getUserinfoById(1); System.out.println(user.getUsername()); } @Test public void testQueryUserinfoList(){ //测试查询所有 List<Userinfo> userList = userBiz.getUserinfoList(); for(Userinfo user : userList){ System.out.println(user.getUsername()); } } }
log4j.properties中没什么变化,也在src下:
log4j.rootLogger = info,CONSOLE,ROLLING_FILE
log4j.addivity.org.apache=true
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=info
log4j.appender.ROLLING_FILE.File=F\:/MyEclipse 9/logs/mysqlweb/rolling.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.ROLLING_FILE.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=10
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern= %d - %c -%-4r [%t] %-5p %c %x - %m%n
##Hibernate log begin##
log4j.logger.org.hibernate=info
log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.HQL=debug
##Hibernate log end##
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
下面是网上搜集来的基于Spring框架的JUnit测试方法,方便以后开发转过来了。感谢原作者。
一、AbstractDependencyInjectionSpringContextTests
public class AuctionUserDaoTest extends AbstractDependencyInjectionSpringContextTests
{
//重写该方法
public String[] getConfigLocations()
{
String[] configLocations = {"daoContext.xml","applicationContext.xml"};
return configLocations;
}
AuctionUserDao auctionUserDao;
public void setAuctionUserDao(AuctionUserDao auctionUserDao) {
this.auctionUserDao = auctionUserDao;
}
public void testFindAll()
{
}
}
单元测试只要继承AbstractDependencyInjectionSpringContextTests,并重写getConfigLocations方法,就可以引入要依赖的bean.继承 AbstractDependencyInjectionSpringContextTests单元测试的方法不会进行回滚。
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
二、AbstractAnnotationAwareTransactionalTests
public class BidDaoTest extends AbstractAnnotationAwareTransactionalTests
{
private BidDao bidDao;
public void setBidDao(BidDao bidDao) {
this.bidDao = bidDao;
}
public String[] getConfigLocations()
{
String[] configLocations = {"daoContext.xml","applicationContext.xml"};
return configLocations;
}
@Rollback(false)
public void testFindByUser()
{
}
}
单元测试继承AbstractAnnotationAwareTransactionalTests,虽然里面有一个注释熟悉Rollback,但是测试了很多次,发现该属性没有效果,不清楚到底还有什么地方要设置一下,继承了AbstractAnnotationAwareTransactionalTests,所有的测试方法都是会回滚,刚好跟AbstractDependencyInjectionSpringContextTests类相反
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
三、@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"../../../applicationContext.xml","../../../daoContext.xml"})
@TransactionConfiguration(transactionManager="transactionManager")
@Transactional
public class KindDaoTest
{
@Autowired
KindDao kindDao;
@Test
@Rollback(false)
public void findAll()
{
}
}
该单元测试的特点:运用注释,使得编写测试更加简单,以及可以设置是否回滚。
@RunWith(SpringJUnit4ClassRunner.class)
表示该测试用例是运用junit4进行测试,也可以换成其他测试框架
@TransactionConfiguration(transactionManager="transactionManager")为可选项,该项不会影响回滚的设置。
@ContextConfiguration(locations={"../../../applicationContext.xml","../../../daoContext.xml"})
该路径的设置时相当于该单元测试所在的路径,也可以用classpath进行设置,该设置还有一个inheritLocations的属性,默认为true,表示子类可以继承该设置。
@Autowired
表示bean自动加载,而不用像之前的两个类要添加一个set的方法。
@Test
表示该方法是测试用例
@Rollback(false)
表示该测试用例不回滚
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
在使用所有注释前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
Spring框架在org.springframework.test.annotation
包中提供了常用的Spring特定的注解集,如果你在Java5或以上版本开发,可以在测试中使用它。
@IfProfileValue
提示一下,注解测试只针对特定的测试环境。 如果配置的ProfileValueSource类返回对应的提供者的名称值, 这个测试就可以启动。这个注解可以应用到一个类或者单独的方法。
@IfProfileValue(name=”java.vendor”, value=”Sun Microsystems Inc.”)
public void testProcessWhichRunsOnlyOnSunJvm() {
// some logic that should run only on Java VMs from Sun Microsystems
}
同时@IfProfileValue可配置一个值列表 (使用OR 语义) 来在JUnit环境中获得TestNG的测试组支持。 看下面的例子:
@IfProfileValue(name=”test-groups”, values={”unit-tests”, “integration-tests”})
public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
// some logic that should run only for unit and integration test groups
}
@ProfileValueSourceConfiguration
类级别注解用来指定当通过@IfProfileValue注解获取已配置的profile值时使用何种ProfileValueSource。 如果@ProfileValueSourceConfiguration没有在测试中声明,将默认使用 SystemProfileValueSource。
@ProfileValueSourceConfiguration(CustomProfileValueSource.class)
public class CustomProfileValueSourceTests {
// class body…
}
@DirtiesContext
在测试方法上出现这个注解时,表明底层Spring容器在该方法的执行中被“污染”,从而必须在方法执行结束后重新创建(无论该测试是否通过)。
@DirtiesContext
public void testProcessWhichDirtiesAppCtx() {
// some logic that results in the Spring container being dirtied
}
@ExpectedException
表明被注解方法预期在执行中抛出一个异常。预期异常的类型在注解中给定。如果该异常的实例在测试方法执行中被抛出, 则测试通过。同样的如果该异常实例没有在测试方法执行时抛出,则测试失败。
@ExpectedException(SomeBusinessException.class)
public void testProcessRainyDayScenario() {
// some logic that should result in an Exception being thrown
}
@Timed
表明被注解的测试方法必须在规定的时间区间内执行完成(以毫秒记)。如果测试执行时间超过了规定的时间区间,测试就失败了。
注意该时间区间包括测试方法本身的执行,任何重复测试(参见 @Repeat),还有任何测试fixture的set up或tear down时间。
Spring的@Timed
注解与JUnit 4的@Test(timeout=...)
支持具有不同的语义。 特别地,鉴于JUnit 4处理测试执行超时(如通过在一个单独的线程
中执行测试方法)的方式, 我们不可能在一个事务上下文中的测试方法上使用JUnit的@Test(timeout=...)
配置。因此, 如果你想将一个测试方法配置成计时且具事务性的, 你就必须联合使用Spring的@Timed
及@Transactional
注解。 还值得注意的是@Test(timeout=...)
只管测试方法本身执行的次数,如果超出的话立刻就会失败; 然而,@Timed
关注的是测试执行的总时间(包括建立和销毁操作以及重复),并且不会令测试失败。
@Timed(millis=1000)
public void testProcessWithOneSecondTimeout() {
// some logic that should not take longer than 1 second to execute
}
@Repeat
表明被注解的测试方法必须重复执行。执行的次数在注解中声明。
注意重复执行范围包括包括测试方法本身的执行,以及任何测试fixture的set up或tear down。
@Repeat(10)
public void testProcessRepeatedly() {
// …
}
@Rollback
表明被注解方法的事务在完成后是否需要被回滚。 如果true,事务将被回滚,否则事务将被提交。 使用@Rollback接口来在类级别覆写配置的默认回滚标志。
@Rollback(false)
public void testProcessWithoutRollback() {
// …
}
@NotTransactional
出现该注解表明测试方法必须不在事务中执行。
@NotTransactional
public void testProcessWithoutTransaction() {
// …
}
Spring TestContext Framework还支持下面这些非特定于测试的注解,并且保持其语义不变。
@Autowired
@Qualifier
-
@Resource
(javax.annotation)如果JSR-250可用 -
@PersistenceContext
(javax.persistence)如果JPA可用 -
@PersistenceUnit
(javax.persistence)如果JPA可用 @Required
@Transactional
@TestExecutionListeners
定义类级别的元数据,TestExecutionListener
s会使用TestContextManager
进行注册。 通常,@TestExecutionListeners
与@ContextConfiguration
会搭配使用。
@ContextConfiguration @TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) public class CustomTestExecutionListenerTests { // class body... }
@TransactionConfiguration
为配置事务性测试定义了类级别的元数据。特别地,如果需要的PlatformTransactionManager不是“transactionManager”的话, 那么可以显式配置驱动事务的PlatformTransactionManager
的bean名字。此外, 可以将defaultRollback
标志改为false
。通常, @TransactionConfiguration
与@ContextConfiguration
搭配使用。
@ContextConfiguration @TransactionConfiguration(transactionManager="txMgr", defaultRollback=false) public class CustomConfiguredTransactionalTests { // class body... }
@BeforeTransaction
表明被注解的public void
方法应该在测试方法的事务开始之前执行, 该事务是通过@Transactional
注解来配置的。
@BeforeTransaction public void beforeTransaction() { // logic to be executed before a transaction is started }
@AfterTransaction
表明被注解的public void
方法应该在测试方法的事务结束之后执行, 该事务是通过@Transactional
注解来配置的。
@AfterTransaction public void afterTransaction() { // logic to be executed after a transaction has ended }
- org.springframework.test-3.0.5.RELEASE.jar (200.5 KB)
- 下载次数: 34
发表评论
-
实例:简单的JDBC复习+MySql入门学习
2011-10-04 11:26 4964万变不离其宗。。持久层怎么变也是JDBC,框架怎么新也是反射机 ... -
Log4j.1.2.14 学习笔记【10月4日更新】
2011-10-03 14:41 1536Log4j学习笔记 2011年10月02日 环境 MyE ... -
JUnit 3.8.2和JUnit 4.8.1学习笔记
2011-10-02 11:54 4232JUnit学习笔记 2011年10月01日 环境 MyE ... -
Spring 3.0 + Struts 1.3 + Hibernate 3.3 框架整合小结
2011-08-29 21:37 1887导读: 前一阵对SS2H整合 ... -
jar文件的运行方式
2011-08-28 09:55 986jar是一种压缩格式,类似于.zip java 的开发工 ... -
知识补充:抽象方法abstract为什么不能与static、synchronized、native混用
2011-08-24 06:35 1612这个问题要从实际的逻辑角度去看的,首先要了解abstract, ... -
知识补充:ArrayList Vector LinkedList 区别与用法
2011-08-21 18:05 769ArrayList 和Vector是采用数组方式存储数据,此数 ... -
知识补充:Servlet与CGI
2011-08-21 17:00 1092一、CGI 1. 定义: CGI(Common G ... -
Action[/***] does not contain specified method (check logs)
2011-08-18 21:25 7021今天利用SS1H框架整合做练习的时候,出现了一个Action中 ... -
收集来的Struts1.x和Struts2的异同
2011-08-18 15:06 829特性 Struts1.x Stru ... -
Spring 3.0 + Struts 2.1 + Hibernate 3.3 框架整合小结
2011-08-17 22:05 3098引言: 学习SSH框架有一阵了,今天对SSH框架整合 ... -
纯JDBC、Hibernate、Spring的AOP声明式事务管理小结
2011-08-16 23:52 1579引言: 最近在中心的 ...
相关推荐
- Log4j日志库 - 连接池(如C3P0、DBCP) - 数据库驱动(如MySQL) ##### 2. 配置Spring支持 - **在web.xml中添加配置** ```xml <!-- Spring上下文加载监听 --> <param-name>contextConfigLocation ...
- 复制`project\etc`目录下的`log4j.properties`配置文件。 - 在`project`目录下搜索并复制`hibernate.cfg.xml`配置文件和所有的`.hbm.xml`映射文件。 - 修改`hibernate.cfg.xml`配置文件,例如设置方言(Dialect...
7. **整合Struts**:为了将Spring与Struts结合,我们需要在Struts的配置文件(如struts.xml)中添加Spring插件配置,并在Action类上使用`@SpringBean`注解注入Service。 8. **测试与运行**:完成上述配置后,可以...
<log4j.version>2.5</log4j.version> <groupId>junit <artifactId>junit <version>4.11 <scope>test <groupId>org.apache.struts <artifactId>struts2-core <version>2.5.1 <groupId>javax....
- `log4j.jar`,位于`/lib/test`目录下。 - `slf4j-log4j12.jar`,位于`/lib/test`目录下。 ##### 1.4 JDBC Driver - **官网地址**:[http://www.mysql.com/downloads/connector/j/]...