1 单元测试
单元测试(Unit Testing), ?即测试功能代码的预期行为和实际行为的差异, 是一种白盒测试。 可以快速的测试自己的程序, 提高代码质量; 也可以用来便捷地测试不熟悉的类库的行为, 熟悉类库。
使用eclipse的junit插件可以快速的建立单元测试:
最简单的例子:
package athena.junit; import static org.junit.Assert.*; import org.junit.Test; public class UnitTest { @Test public void test() { String str = "abcde"; String sub = str.substring(3, 5); assertEquals("de", sub); } } |
@Test, 表示这是一段测试代码, 将由junit调用。
assertEquals是junit提供的测试方法, 第一个参数是期望的值, 第二个参数是实际的值, 如果两个参数不相等, 会抛出错误使测试失败; assertEquals有多个重载方法。
详细的单元测试知识可以参考:http://blog.csdn.net/zhangxin09/article/details/42418441
2 spring项目中的单元测试
好了, 该进入正题了,我们的重点是在spring项目中进行单元测试。
spring的程序代码需要spring环境如数据库、 DI(依赖注入)环境才可以正常运行, 所以要为单元测试代码加入执行环境注解, 让单元测试在预期的环境中运行。
简单的例子:
package athena.section.service.impl; import static org.junit.Assert.*; 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 org.springframework.transaction.annotation.Transactional; @ContextConfiguration(locations = { "/spring-mvc.xml", "/spring-mybatis.xml","/spring-jms.xml", }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class DemoServiceImplTest { @Test public void testDbConnection() { //这样单元测试代码就可以做执行数据库等操作了 } } |
使用@ContextConfiguration和@RunWith注解配置spring的测试环境, @Transactional表示这个单元测试对数据的增加修改都会被回滚, 不会真正的影响数据库。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。