Seam工程要能够运行单元测试首先要把JBoss Embedded容器环境搭建起来
还是采用搭建Tomcat时候的embedded-jboss-beta3.SP10
1. 将JBoss Embedded的容器中的bootstrap目录下的东西复制到java工程的测试环境下,例如:src/test/resources
2. 在测试环境下建立WEB-INF目录,复制实际发布的WEB-INF目录下的东西到此目录
3. 复制hibernate.cfg.xml,seam.properties等项目配置到测试环境的根目录下,例如:src/test/resources
<目录结构可以参考附件图片>
4. 采用如下的maven配置,搭建相应的lib库
<!-- Unit Test --> <dependency> <groupId>org.jboss.seam.embedded</groupId> <artifactId>hibernate-all</artifactId> <version>beta3.SP12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.seam.embedded</groupId> <artifactId>jboss-embedded-all</artifactId> <version>beta3.SP12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.seam.embedded</groupId> <artifactId>thirdparty-all</artifactId> <version>beta3.SP12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.seam.embedded</groupId> <artifactId>jboss-embedded-api</artifactId> <version>beta3.SP12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.jboss.microcontainer</groupId> <artifactId>jboss-deployers-client-spi</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>5.9</version> <scope>test</scope> </dependency>
这样,单元测试的微环境搭建成功
接下来编写单元测试的样例, 所有的单元测试类都要继承与SeamTest类
public class UserDaoTest extends SeamTest { @Test public void testCRUD() throws Exception { new FacesRequest() { @Override protected void invokeApplication() throws Exception { User user = new User(); user.setUsername("Kevin Chen"); user.setPassword("Orz"); IUserDao userDao = (IUserDao) getValue("#{userDao}"); // 获取注入对象 Assert.assertNotNull(userDao); userDao.save(user); System.out.println(user.getId()); Assert.assertNotNull(userDao.get(user.getId())); user.setUsername("Kingdom Sky"); userDao.update(user); User user2 = userDao.get(user.getId()); System.out.println(user2.getUsername()); Assert.assertEquals(user2.getUsername(), user.getUsername()); Assert.assertEquals(userDao.get(user.getId()).getUsername(), "Kingdom Sky"); List<User> users = userDao.findByCriteria(); System.out.println(users.size()); for (User u : users) { System.out.println("Username : " + u.getUsername()); } } }.run(); } }
最后,要在eclipse下运行单元测试,需要安装TestNG插件