一.JUnit介绍

JUnit是Java中最有名的单元测试框架,用于编写和运行可重复的测试,多数Java的开发环境都已经集成了JUnit作为单元测试的工具。好的单元测试能极大的提高开发效率和代码质量。

测试类命名规则:被测试类+Test,如UserServiceTest
测试用例命名规则:test+用例方法,如testGet

Maven导入junit、sprint-test 、json-path相关测试包,并配置maven-suerfire-plugin插件,编辑pom.xml

  1. <dependencies>
  2. <!-- Test Unit -->
  3. <dependency>
  4. <groupId>junit</groupId>
  5. <artifactId>junit</artifactId>
  6. <version>4.12</version>
  7. <scope>test</scope>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework</groupId>
  11. <artifactId>spring-test</artifactId>
  12. <version>4.3.10.RELEASE</version>
  13. <scope>test</scope>
  14. </dependency>
  15. <!-- Json断言测试 -->
  16. <dependency>
  17. <groupId>com.jayway.jsonpath</groupId>
  18. <artifactId>json-path</artifactId>
  19. <version>2.4.0</version>
  20. <scope>test</scope>
  21. </dependency>
  22. </dependencies>
  23. <build>
  24. <plugins>
  25. <!-- 单元测试插件 -->
  26. <plugin>
  27. <groupId>org.apache.maven.plugins</groupId>
  28. <artifactId>maven-surefire-plugin</artifactId>
  29. <version>2.20</version>
  30. <dependencies>
  31. <dependency>
  32. <groupId>org.apache.maven.surefire</groupId>
  33. <artifactId>surefire-junit4</artifactId>
  34. <version>2.20</version>
  35. </dependency>
  36. </dependencies>
  37. <configuration>
  38. <!-- 是否跳过测试 -->
  39. <skipTests>false</skipTests>
  40. <!-- 排除测试类 -->
  41. <excludes>
  42. <exclude>**/Base*</exclude>
  43. </excludes>
  44. </configuration>
  45. </plugin>
  46. </plugins>
  47. </build>

二.Service层测试示例

创建Service层测试基类,新建BaseServiceTest.java

  1. // 配置Spring中的测试环境
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. // 指定Spring的配置文件路径
  4. @ContextConfiguration(locations = {"classpath*:/spring/applicationContext.xml"})
  5. // 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
  6. @Transactional(transactionManager = "transactionManager")
  7. // 指定数据库操作不回滚,可选
  8. @Rollback(value = false)
  9. public class BaseServiceTest {
  10. }

测试UserService类,新建测试类UserServiceTest.java

  1. public class UserServiceTest extends BaseServiceTest {
  2.  
  3. private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class);
  4.  
  5. @Resource
  6. private UserService userService;
  7.  
  8. @Test
  9. public void testGet() {
  10. UserDO userDO = userService.get(1);
  11.  
  12. Assert.assertNotNull(userDO);
  13. LOGGER.info(userDO.getUsername());
  14.  
  15. // 增加验证断言
  16. Assert.assertEquals("testGet faield", "Google", userDO.getUsername());
  17. }
  18. }

三.Controller层测试示示例

创建Controller层测试基类,新建BaseControllerTest.java

  1. // 配置Spring中的测试环境
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. // 指定测试环境使用的ApplicationContext是WebApplicationContext类型的
  4. // value指定web应用的根
  5. @WebAppConfiguration(value = "src/main/webapp")
  6. // 指定Spring容器层次和配置文件路径
  7. @ContextHierarchy({
  8. @ContextConfiguration(name = "parent", locations = {"classpath*:/spring/applicationContext.xml"}),
  9. @ContextConfiguration(name = "child", locations = {"classpath*:/spring/applicationContext_mvc.xml"})
  10. })
  11. // 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
  12. @Transactional(transactionManager = "transactionManager")
  13. // 指定数据库操作不回滚,可选
  14. @Rollback(value = false)
  15. public class BaseControllerTest {
  16. }

测试IndexController类,新建测试类IndexControllerTest.java

  1. public class IndexControllerTest extends BaseControllerTest {
  2.  
  3. private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class);
  4.  
  5. // 注入webApplicationContext
  6. @Resource
  7. private WebApplicationContext webApplicationContext;
  8.  
  9. private MockMvc mockMvc;
  10.  
  11. // 初始化mockMvc,在每个测试方法前执行
  12. @Before
  13. public void setup() {
  14. this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
  15. }
  16.  
  17. @Test
  18. public void testIndex() throws Exception {
  19. /**
  20. * mockMvc.perform()执行一个请求
  21. * get("/server/get")构造一个请求
  22. * andExpect()添加验证规则
  23. * andDo()添加一个结果处理器
  24. * andReturn()执行完成后返回结果
  25. */
  26. MvcResult result = mockMvc.perform(get("/server/get")
  27. .param("id", "1"))
  28. .andExpect(MockMvcResultMatchers.status().isOk())
  29. .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Google"))
  30. .andDo(print())
  31. .andReturn();
  32.  
  33. LOGGER.info(result.getResponse().getContentAsString());
  34.  
  35. // 增加验证断言
  36. Assert.assertNotNull(result.getResponse().getContentAsString());
  37. }
  38. }

四.执行单元测试

工程测试目录结构如下,运行mvn test命令,自动执行maven-suerfire-plugin插件

执行结果

五.异常情况

执行测试用例时可能抛BeanCreationNotAllowedException异常

  1. [11 20:47:18,133 WARN ] [Thread-3] (AbstractApplicationContext.java:994) - Exception thrown from ApplicationListener handling ContextClosedEvent
  2. org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'sessionFactory': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
  3. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:216)
  4. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  5. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  6. at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:235)
  7. at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:192)
  8. at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)

通过注入DefaultLifecycleProcessor解决,编辑resources/spring/applicationContext.xml

  1. <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
  2. <property name="timeoutPerShutdownPhase" value="10000"/>
  3. </bean>

Spring+JUnit4单元测试入门的更多相关文章

  1. JUnit4单元测试入门教程

    本文按以下顺序讲解JUnit4的使用 下载jar包 单元测试初体验 自动生成测试类 执行顺序 @Test的属性 下载jar包## 下载地址 在github上,把以下两个jar包都下载下来.     下 ...

  2. Spring AOP初级——入门及简单应用

      在上一篇<关于日志打印的几点建议以及非最佳实践>的末尾提到了日志打印更为高级的一种方式——利用Spring AOP.在打印日志时,通常都会在业务逻辑代码中插入日志打印的语句,这实际上是 ...

  3. ActiveMQ (三) Spring整合JMS入门

    Spring整合JMS入门 前提:安装好了ActiveMQ  ActiveMQ安装 Demo结构:   生产者项目springjms_producer: pom.xml <?xml versio ...

  4. Spring Mvc的入门

    SpringMVC也叫Spring Web mvc,属于表现层的框架.Spring MVC是Spring框架的一部分,是在Spring3.0后发布的. Spring Web MVC是什么: Sprin ...

  5. Spring之单元测试

    引言 是否在程序运行时使用单元测试是衡量一个程序员素质的一个重要指标.使用单元测试既可以让我检查程序逻辑的正确性还可以让我们减少程序测试的BUG,便于调试可以提高我们写程序的效率.以前我们做单元测试的 ...

  6. SpringBoot使用Junit4单元测试

    SpringBoot2.0笔记 本篇介绍Springboot单元测试的一些基本操作,有人说一个合格的程序员必须熟练使用单元测试,接下来我们一起在Springboot项目中整合Junit4单元测试. 本 ...

  7. Spring Cloud 从入门到精通

    Spring Cloud 是一套完整的微服务解决方案,基于 Spring Boot 框架,准确的说,它不是一个框架,而是一个大的容器,它将市面上较好的微服务框架集成进来,从而简化了开发者的代码量. 本 ...

  8. Spring MVC学习总结(1)——Spring MVC单元测试

    关于spring MVC单元测试常规的方法则是启动WEB服务器,测试出错 ,停掉WEB 改代码,重启WEB,测试,大量的时间都浪费在WEB服务器的启动上,下面介绍个实用的方法,spring MVC单元 ...

  9. Spring Junit4 接口测试

    Junit实现接口类测试 - dfine.sqa - 博客园http://www.cnblogs.com/Automation_software/archive/2011/01/24/1943054. ...

随机推荐

  1. Postman几种常用方式

    Postman几种常用方式 1.get请求直接拼URL形式 对于http接口,有get和post两种请求方式,当接口说明中未明确post中入参必须是json串时,均可用url方式请求 参数既可以写到U ...

  2. Centos7.2下基于Nginx+Keepalived搭建高可用负载均衡(一.基于Keepalived搭建HA体系)

    说明 本文只为方便日后查阅,不对一些概念再做赘述,网上都有很多明确的解释,也请大家先了解相关概念. 两台搭建HA的服务器是华为云上的ECS(不要忘记开通VPC,保证我们的服务器都处在一个内网环境),由 ...

  3. [转载]在instagram上面如何利用电脑来上传图片

    原文地址:在instagram上面如何利用电脑来上传图片作者:小北的梦呓 我们都知道instagram是一个手机版的app,instagram官方不支持通过电脑来上传图片,而利用手机又很麻烦,那么如果 ...

  4. 201521123107 《Java程序设计》第14周学习总结

    第14周-数据库 1.本周学习总结 2.书面作业 1. MySQL数据库基本操作 建立数据库,将自己的姓名.学号作为一条记录插入.(截图,需出现自己的学号.姓名) 在自己建立的数据库上执行常见SQL语 ...

  5. 201521123109《java程序设计》第八周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 1.2 选做:收集你认为有用的代码片段 2. 书面作业 本次作业题集集合 List中指定元素的删除(题目4-1 ...

  6. 201521123013 《Java程序设计》第5周学习总结

    1. 本章学习总结 1.1 尝试使用思维导图总结有关多态和接口的知识点. 1.2可选 使用常规方法总结其他上课内容. 接口:不是类,不能使用new实例化,可用instanceof判断是否实现某接口.接 ...

  7. [转载]sqlserver、Mysql、Oracle三种数据库的优缺点总结

    一.sqlserver优点:易用性.适合分布式组织的可伸缩性.用于决策支持的数据仓库功能.与许多其他服务器软件紧密关联的集成性.良好的性价比等:为数据管理与分析带来了灵活性,允许单位在快速变化的环境中 ...

  8. java课程设计——猜数游戏

    1.团队课程设计博客链接 http://www.cnblogs.com/springbreezemiles/p/7064135.html 2.个人负责模块或任务说明 本人任务: 编写主界面以及排行榜代 ...

  9. 2017年9月19日 JavaScript语法操作

    关于JavaScript个人还是觉得比较有意思的 {在</html>后面写或者在</body>前面写(必须紧贴</body>)} <script> va ...

  10. Tiled Editor 图块的两种导入方式

    一.图块集图块的导入. 打开或者创建地图后,新建 新图块. 弹出新图块面板 图块类型选择 "基于图块集图块",一定要选择"嵌入地图",否则需要另存为其他类型的文 ...