首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring3单元测试跟集成测试

2012-08-01 
Spring3单元测试和集成测试project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w

Spring3单元测试和集成测试
<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 dtdDefault 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>

2 测试spring mvc的controler

public class LoginControllerTest {@Testpublic 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");}}


3利用easymock对userService类做单元测试
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);}}



4 利用Dbunit对userDao做单元测试

  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, "" );}@Resourceprivate JdbcTemplate jdbcTemplate;@Autowiredprotected UserDao userDao;@Autowiredprivate DataSource dataSource;private IDatabaseConnection conn;@Beforepublic 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@Transactionalpublic void testCleanInsertInitial() {String sqlStr = " select count(*) from t_login_log where login_log_id = '9'";int count = jdbcTemplate.queryForInt(sqlStr);Assert.assertEquals(1, count);}@Overrideprotected 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 {@Resourceprivate JdbcTemplate jdbcTemplate;@Autowiredprotected UserService userService;@Beforepublic 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());}@Testpublic 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");}@Afterpublic void after() {System.out.println("after");}}


引用
了解 dbunit,easy mock,spring3,maven的资源
http://newwhx2011.iteye.com/blog/1089559
http://www.dbunit.org/howto.html
http://www.iteye.com/topic/475172

热点排行