Spring3单元测试和集成测试

[quote]本文针对常见的springmvc+spring+springjdbc的架构提供啦一些单元测试和集成测试的范例,附件是完整的demo
[/quote]


[b]示例代码安装:
1 安装maven
2 准备mysql数据库,运行脚本: Spring3\schema\sampledb.sql
3 maven dbunit:export可以导出数据库数据到export.xml
4 maven test可以测试所有testing 代码
5 maven jetty:run 可以启动jetty服务器
[/b]


[b]1. maven pom 文件[/b]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wilson</groupId>
<artifactId>Spring3</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Spring3 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.6.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.0.6.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.6.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.6.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<finalName>Spring3</finalName>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.0.4.v20111024</version>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>dbunit-maven-plugin</artifactId>
<version>1.0-beta-3</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
</dependencies>

<configuration>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost/sampledb</url>
<username>root</username>
<password>root</password>
<type>CLEAN_INSERT</type>
<!-- ataset file format type. Valid types are: flat, xml, csv, and dtd
Default value is: xml. -->
<format>xml</format>
<src>src/test/resources/export.xml</src>
<dest>src/test/resources/export.xml</dest>
</configuration>

<executions>
<execution>
<phase>process-test-classes</phase>
<goals>
<goal>operation</goal>
</goals>
<!-- specific configurations 我们可以在这里指定不同的配置-->
<configuration>
<format>xml</format>
<src>src/test/resources/export.xml</src>
<type>CLEAN_INSERT</type>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

[b]
2 测试spring mvc的controler[/b]
public class LoginControllerTest {

@Test
public void testingHandlerWithUserInSession() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
// LoginCommand command = new LoginCommand();
MockHttpSession session = new MockHttpSession();
session.setAttribute("user", new User());
request.setSession(session);

LoginController controller = new LoginController();
ModelAndView mv1 = controller.handle(request, null, null, null);
assertEquals(mv1.getViewName(), "target");
}
}


[b]3利用easymock对userService类做单元测试[/b]
public class UserServiceImplTest extends TestCase {
public void testHasMatchUser() {
System.out.println("teste1");
UserServiceImpl s = new UserServiceImpl();
UserDao dao = EasyMock.createMock(UserDao.class);
s.setUserDao(dao);

EasyMock.expect(dao.getMatchCount("tom", "1231")).andReturn(1);
EasyMock.expect(dao.getMatchCount("tom", "234")).andReturn(0);

EasyMock.replay(dao);

assertEquals(s.hasMatchUser("tom", "1231"), true);
assertEquals(s.hasMatchUser("tom", "234"), false);

}
}


[b]
4 利用Dbunit对userDao做单元测试
[/b]
dbunit的测试数据
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<table name="t_user">
<column>user_id</column>
<column>user_name</column>
<column>credits</column>
<column>password</column>
<column>last_visit</column>
<column>last_ip</column>
<row>
<value>3</value>
<value>user001</value>
<null/>
<value>123456</value>
<null/>
<null/>
</row>
</table>
</dataset>


测试dao
package com.baobaotao.dao.jdbc;
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@ContextConfiguration(locations={"classpath:baobaotao-dao.xml","classpath:baobaotao-service.xml"})
public class UserDaoTest extends DBTestCase {
public UserDaoTest() {
super();
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "com.mysql.jdbc.Driver" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:mysql://localhost/sampledb" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "root" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "root" );
// System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, "" );
}

@Resource
private JdbcTemplate jdbcTemplate;

@Autowired
protected UserDao userDao;

@Autowired
private DataSource dataSource;

private IDatabaseConnection conn;

@Before
public void initDbunit() throws Exception {
super.setUp();
conn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
}

// @Test
@Timed(millis=1000)
public void testRegisterUser() throws SQLException, IOException, DatabaseUnitException, ParseException {
// SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy");
User user = new User();
user.setUserId(3);
user.setUserName("user001");
user.setPassword("123456");
// user.setCredits(40);
// user.setLastIp("192.168.12.7");
// user.setLastVisit(dateFormatter.parse("24.11.2011"));
userDao.RegisterUser(user);

QueryDataSet actual = new QueryDataSet(conn);
actual.addTable("t_user",
"select * from t_user where t_user.user_name = 'user001'");

IDataSet expected = new XmlDataSet(new ClassPathResource("com/baobaotao/dao/jdbc/user001.xml").getInputStream());

Assertion.assertEquals(expected, actual);
}

@Test
@Transactional
public void testCleanInsertInitial() {
String sqlStr = " select count(*) from t_login_log where login_log_id = '9'";
int count = jdbcTemplate.queryForInt(sqlStr);
Assert.assertEquals(1, count);
}

@Override
protected IDataSet getDataSet() throws Exception {
return new XmlDataSet(new ClassPathResource("export.xml").getInputStream());
}

}


5 利用spring的test包做集成测试
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@ContextConfiguration(locations={"classpath:baobaotao-dao.xml","classpath:baobaotao-service.xml"})
public class UserServiceIntegrateWithJdbcTestSpring3 {
@Resource
private JdbcTemplate jdbcTemplate;

@Autowired
protected UserService userService;

@Before
public void prepareTestData() {
System.out.println("before");
}

@Test
@Timed(millis=1000)
public void testRegisterUser() {
User user = new User();
// user.setUserId(2);
user.setUserName("johnaaaa");
user.setPassword("123456");
userService.registerUser(user);

String sqlStr = " select user_id from t_user where user_name = 'johnaaaa'";
int userId = jdbcTemplate.queryForInt(sqlStr);
Assert.assertEquals(userId, user.getUserId());
}

@Test
public void testUserMatchService() {
User user = new User();
// user.setUserId(2);
user.setUserName("wilson");
user.setPassword("123456");
userService.registerUser(user);

Assert.assertFalse(userService.hasMatchUser("john11", "123456"));
Assert.assertTrue(userService.hasMatchUser("wilson", "123456"));
}

//要求测试方法丢出异常
@Test
@ExpectedException(RuntimeException.class)
public void testThrowException() {
throw new RuntimeException("test");
}

@After
public void after() {
System.out.println("after");
}
}


[quote]
了解 dbunit,easy mock,spring3,maven的资源
[url]http://newwhx2011.iteye.com/blog/1089559[/url]
[url]http://www.dbunit.org/howto.html[/url]
[url]http://www.iteye.com/topic/475172[/url]
[/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值