Spring框架概述

Spring大约包含了20个模块,这些模块组成了核心容器(Core Container)、数据访问/集成(Data Access/Integration)、Web、AOP(面向切面编程,Aspect Oriented Programming)、Instrumentation、消息处理(Messaging)和测试(Test),如下图:

spring-test模块通过JUnit和TestNG组件支持单元测试和集成测试。它提供了一致性地加载和缓存Spring上下文,也提供了用于单独测试代码的模拟对象(mock object)。

Spring和Spring MVC的区别

spring 是是一个开源框架,是为了解决企业应用程序开发,功能如下

  • 目的:解决企业应用开发的复杂性
  • 功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
  • 范围:任何Java应用

简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
Spring的两大核心AOP与IOC,可以单独用于任何应用,包括与Struts等MVC框架与Hibernate等ORM框架的集成,目前很多公司所谓的轻量级开发就是用 Spring + Struts(2)+Hibernate。

spring mvc类似于struts的一个MVC开框架,其实都是属于spring,spring mvc需要有spring的架包作为支撑才能跑起来

测试Spring项目

开发环境:

  • jdk1.8
  • IDEA 2017
  • maven 3.5

项目结构如下:

首先创建Maven项目,添加Spring Test支持:

<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.1.5.RELEASE</version>
</dependency>
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version>
</dependency>

TestBean

package com.fsj.ex01;public class TestBean {private String content;public TestBean(String content) {super();this.content = content;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}

TestConfig

package com.fsj.ex01;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;@Configuration
public class TestConfig {@Bean // 声明当前方法的返回值是一个bean@Profile("dev")public TestBean devTestBean() {return new TestBean("from development profile");}@Bean@Profile("prod")public TestBean prodTestBean() {return new TestBean("from production profile");}}

Main

package com.fsj.ex01;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args) {//使用AnnotationConfigApplicationContext实例化Spring容器AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext();context.getEnvironment().setActiveProfiles("dev"); //激活profilecontext.register(TestConfig.class);// 注册bean配置类。context.refresh(); //刷新容器TestBean demoBean = context.getBean(TestBean.class);System.out.println(demoBean.getContent());context.close();}
}

DemoBeanIntegrationTest

package com.fsj.ex01;import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class) //表示该测试用例是运用junit4进行测试,也可以换成其他测试框架
@ContextConfiguration(classes = {TestConfig.class}) //此注解用来加载配置ApplicationContext
@ActiveProfiles("prod") //声明活动的profile
public class DemoBeanIntegrationTests {@Autowired //注入beanprivate TestBean testBean;@Test //@Test标注在方法前,表示其是一个测试的方法 无需在其配置文件中额外设置属性.public void prodBeanShouldInject(){String expected = "from production profile";String actual = testBean.getContent();Assert.assertEquals(expected, actual);}@Beforepublic void beforeMethod(){System.out.println("before all tests");}@Afterpublic void afterMethod(){System.out.println("after all tests.");}
}

其中,RunWith注解表示JUnit将不会跑其内置的测试,而是运行所引用的类中的所有测试

http://junit.sourceforge.net/javadoc/org/junit/runner/RunWith.html

@Retention(value=RUNTIME)
@Target(value=TYPE)
@Inherited
public @interface RunWith

When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit.

启动Main运行项目。

启动DemoBeanIntegrationTests测试本项目。

测试Spring MVC项目

和Spring项目类似,项目完成后,在src/test/java下编写对应的测试用例。

不同的是,为了测试web项目,需要一些Servlet相关的模拟对象,比如:MockMVC / MockHttpServletRequest / MockHttpServletResponse / MockHttpSession等等。

TestControllerIntegration

package com.fsj.ex02;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;import com.fsj.ex02.MyMvcConfig;
import com.fsj.ex02.service.DemoService;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources") //1 此注解指定web资源的位置,默认为src/main/webapp
public class TestControllerIntegrationTests {private MockMvc mockMvc; //2 模拟MVC对象@Autowiredprivate DemoService demoService;//3 在测试用例注入spring的bean@Autowired WebApplicationContext wac; //4 注入WebApplicationContext@Autowired MockHttpSession session; //5 注入模拟的http session@Autowired MockHttpServletRequest request; // 模拟request@Before //7 测试开始前的初始化工作public void setup() {mockMvc =MockMvcBuilders.webAppContextSetup(this.wac).build(); //2}@Testpublic void testNormalController() throws Exception{String exp_str = demoService.saySomething(); // expect strmockMvc.perform(get("/normal")) //8 模拟GET /normal.andExpect(status().isOk())//9 预期返回状态为200.andExpect(view().name("page"))//10 预期view的名称.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//11 预期页面转向的真正路径.andExpect(model().attribute("msg", exp_str));//12 预期model里的值}@Testpublic void testRestController() throws Exception{mockMvc.perform(get("/testRest")) //13 GET.andExpect(status().isOk()).andExpect(content().contentType("text/plain;charset=UTF-8"))//14.andExpect(content().string(demoService.saySomething()));//15}
}

完整项目在: https://github.com/shenjiefeng/spring-fortest

运行结果:

拾遗

使用AnnotationConfigApplicationContext实例化Spring容器

AnnotationConfigApplicationContext是在Spring 3.0中新增的。这个多功能的ApplicationContext实现即可接收@Configuration类作为输入,也可接收普通的@Component类,及使用JSR-330元数据注解的类。

当将@Configuration类作为输入时,@Configuration类本身被注册为一个bean定义,并且该类中所有声明的@Bean方法也被注册为bean定义。

当将@Component和JSR-330类作为输入时,它们被注册为bean定义,并且在需要的地方使用DI元数据,比如@Autowired或@Inject。

构造器实例化跟实例化一个ClassPathXmlApplicationContext时将Spring XML文件用作输入类似,在实例化一个AnnotationConfigApplicationContext时可以使用@Configuration类作为输入。这就允许Spring容器完全零XML配置:

public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);MyService myService = ctx.getBean(MyService.class);myService.doStuff();
}

如上所述,AnnotationConfigApplicationContext不局限于仅仅使用@Configuration类。不论什么@Component或JSR-330注解的类都能够作为AnnotationConfigApplicationContext构造器的输入。比如:

public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class);MyService myService = ctx.getBean(MyService.class);myService.doStuff();
}

参考

  1. http://blog.csdn.net/tangtong1/article/details/51326887
  2. Spring Boot 实战
  3. Spring测试框架JUnit4.4

转载于:https://www.cnblogs.com/lawlietfans/p/7667518.html

如何在Spring和Spring MVC项目中进行测试相关推荐

  1. spring mvc项目中利用freemarker生成自定义标签

    2019独角兽企业重金招聘Python工程师标准>>> spring mvc项目中利用freemarker生成自定义标签 博客分类: java spring mvc +freemar ...

  2. 转 mvc项目中,解决引用jquery文件后智能提示失效的办法

    mvc项目中,解决用Url.Content方法引用jquery文件后智能提示失效的办法 这个标题不知道要怎么写才好, 但是希望文章的内容对大家有帮助. 场景如下: 我们在用开发开发程序的时候,经常会引 ...

  3. ajax调用fastreport,使用Ajax更新ASP.Net MVC项目中的报表对象

    Ajax技术显著加快了Web应用程序的速度.另外,视觉效果方面也有提升.大家都同意,每次点击按钮时整个页面都会被刷新这一点不太友好.如果你的网速不是很快,那么这个过程会很烦人,因为所有的元素都会先消失 ...

  4. 在已有的Asp.net MVC项目中引入Taurus.MVC

    Taurus.MVC是一个优秀的框架,如果要应用到已有的Asp.net MVC项目中,需要修改一下. 1.前提约定: 走Taurus.MVC必须指定后缀.如.api 2.原项目修改如下: web.co ...

  5. MVC项目中用户权限的限制

    MVC项目中用户权限的限制 开发工具与关键技术: MVC 作者:姚智颖 撰写时间:2020/08/16 注释:下面以机订票系统中角色维护功能为例,设置其中不同级别的用户在整个系统中一些功能的访问权限. ...

  6. MVC项目中数据的分离

    MVC项目中数据的分离 注释:下面以飞机电子客票系统中PNR查询功能为例,对未出票的PNR进行数据分离. 1.在进行旅客信息分离前要进行旅客PNR查询,查询该PNR中有多少个旅客,因为前面已经查询出了 ...

  7. spring MVC项目中,欢迎页首页根路径

    参考:http://iammr.7.blog.163.com/blog/static/49102699201222643458216 0. 问题: 如何改mvc中项目的欢迎页,或者叫做根路径 一个东西 ...

  8. Java程序员必会的Spring AOP在实际项目中的应用

    很久没有用过Java的AOP,最近接触到了一个需求,恰好可以用AOP的思想来实现,就此总结一下. 目录 AOP简介 ① pointcut(切入点) ② advice(通知) ③ aspect(切面) ...

  9. Spring Security 在互联网项目中的实战分享

    SpringBoot 和 Spring Cloud 中默认都是使用 Spring Security框架,这门技术非学不可.那么我们在企业中该如何灵活的运用它呢? 本场 Chat 将通过以下几个方面进行 ...

最新文章

  1. 5G和AI机器人平台
  2. R语言ggplot2可视化条形图(bar plot)、并为条形图添加误差条(error bar)、自定义设置误差条(error bar)的颜色/色彩( Barplots with Error bar)
  3. JDBC(与Orcale的连接)(转)
  4. 探索MySQL高可用架构之MHA(6)
  5. OpenPitrix 是一款开源多云应用程序管理系统
  6. spring学习(50):延迟加载
  7. 嵌入式操作系统内核原理和开发(实时系统中的定时器)
  8. java开发微信提现_java 微信提现至零钱
  9. C#正则表达式之字符替换!...
  10. 电信光猫获取超级账户和密码
  11. python最小二乘法求a b_最小二乘法公式推导及Python实现
  12. 网络计算模式复习大纲
  13. PhotoShop制作gif动态广告效果示例
  14. go 变量大写_go语言如何将大写转小写,c语言字符串小写转大写
  15. 智慧物流在大宗货运领域“落地”有多难?
  16. 阿里云服务器绑定域名,阿里云esc绑定域名,阿里云域名备案
  17. 2023软考信息系统项目管理师论文写作
  18. PX4飞控之PWM输出控制
  19. 基于SSM的人事员工管理系统
  20. 萧井陌 python培训千锋为中钞研究院提供Python培训,助力企业高效数据运营

热门文章

  1. Jersey Restful Application with tomcat
  2. 用友BQ商业智能设计模式——概述
  3. 发现自己竟然有点恐高,郁闷
  4. Java之品优购课程讲义_day01(8)
  5. ORACLE常用性能监控SQL【一】
  6. sizeof和strlen解析
  7. Linux用户、群组管理
  8. DBMS_STATS.GATHER_TABLE_STATS详解
  9. 两台主机ssh的测试及配置
  10. 在线转换Postgresql 到Mysql