javascript
如何在Spring和Spring MVC项目中进行测试
Spring框架概述
Spring大約包含了20個(gè)模塊,這些模塊組成了核心容器(Core Container)、數(shù)據(jù)訪問(wèn)/集成(Data Access/Integration)、Web、AOP(面向切面編程,Aspect Oriented Programming)、Instrumentation、消息處理(Messaging)和測(cè)試(Test),如下圖:
spring-test模塊通過(guò)JUnit和TestNG組件支持單元測(cè)試和集成測(cè)試。它提供了一致性地加載和緩存Spring上下文,也提供了用于單獨(dú)測(cè)試代碼的模擬對(duì)象(mock object)。
Spring和Spring MVC的區(qū)別
spring 是是一個(gè)開源框架,是為了解決企業(yè)應(yīng)用程序開發(fā),功能如下
- 目的:解決企業(yè)應(yīng)用開發(fā)的復(fù)雜性
- 功能:使用基本的JavaBean代替EJB,并提供了更多的企業(yè)應(yīng)用功能
- 范圍:任何Java應(yīng)用
簡(jiǎn)單來(lái)說(shuō),Spring是一個(gè)輕量級(jí)的控制反轉(zhuǎn)(IoC)和面向切面(AOP)的容器框架。
Spring的兩大核心AOP與IOC,可以單獨(dú)用于任何應(yīng)用,包括與Struts等MVC框架與Hibernate等ORM框架的集成,目前很多公司所謂的輕量級(jí)開發(fā)就是用 Spring + Struts(2)+Hibernate。
spring mvc類似于struts的一個(gè)MVC開框架,其實(shí)都是屬于spring,spring mvc需要有spring的架包作為支撐才能跑起來(lái)
測(cè)試Spring項(xiàng)目
開發(fā)環(huán)境:
- jdk1.8
- IDEA 2017
- maven 3.5
項(xiàng)目結(jié)構(gòu)如下:
首先創(chuàng)建Maven項(xiàng)目,添加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 // 聲明當(dāng)前方法的返回值是一個(gè)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實(shí)例化Spring容器AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext();context.getEnvironment().setActiveProfiles("dev"); //激活profilecontext.register(TestConfig.class);// 注冊(cè)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) //表示該測(cè)試用例是運(yùn)用junit4進(jìn)行測(cè)試,也可以換成其他測(cè)試框架 @ContextConfiguration(classes = {TestConfig.class}) //此注解用來(lái)加載配置ApplicationContext @ActiveProfiles("prod") //聲明活動(dòng)的profile public class DemoBeanIntegrationTests {@Autowired //注入beanprivate TestBean testBean;@Test //@Test標(biāo)注在方法前,表示其是一個(gè)測(cè)試的方法 無(wú)需在其配置文件中額外設(shè)置屬性.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將不會(huì)跑其內(nèi)置的測(cè)試,而是運(yùn)行所引用的類中的所有測(cè)試
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.
啟動(dòng)Main運(yùn)行項(xiàng)目。
啟動(dòng)DemoBeanIntegrationTests測(cè)試本項(xiàng)目。
測(cè)試Spring MVC項(xiàng)目
和Spring項(xiàng)目類似,項(xiàng)目完成后,在src/test/java下編寫對(duì)應(yīng)的測(cè)試用例。
不同的是,為了測(cè)試web項(xiàng)目,需要一些Servlet相關(guān)的模擬對(duì)象,比如: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資源的位置,默認(rèn)為src/main/webapp public class TestControllerIntegrationTests {private MockMvc mockMvc; //2 模擬MVC對(duì)象@Autowiredprivate DemoService demoService;//3 在測(cè)試用例注入spring的bean@Autowired WebApplicationContext wac; //4 注入WebApplicationContext@Autowired MockHttpSession session; //5 注入模擬的http session@Autowired MockHttpServletRequest request; // 模擬request@Before //7 測(cè)試開始前的初始化工作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 預(yù)期返回狀態(tài)為200.andExpect(view().name("page"))//10 預(yù)期view的名稱.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//11 預(yù)期頁(yè)面轉(zhuǎn)向的真正路徑.andExpect(model().attribute("msg", exp_str));//12 預(yù)期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} }完整項(xiàng)目在: https://github.com/shenjiefeng/spring-fortest
運(yùn)行結(jié)果:
拾遺
使用AnnotationConfigApplicationContext實(shí)例化Spring容器
AnnotationConfigApplicationContext是在Spring 3.0中新增的。這個(gè)多功能的ApplicationContext實(shí)現(xiàn)即可接收@Configuration類作為輸入,也可接收普通的@Component類,及使用JSR-330元數(shù)據(jù)注解的類。
當(dāng)將@Configuration類作為輸入時(shí),@Configuration類本身被注冊(cè)為一個(gè)bean定義,并且該類中所有聲明的@Bean方法也被注冊(cè)為bean定義。
當(dāng)將@Component和JSR-330類作為輸入時(shí),它們被注冊(cè)為bean定義,并且在需要的地方使用DI元數(shù)據(jù),比如@Autowired或@Inject。
構(gòu)造器實(shí)例化跟實(shí)例化一個(gè)ClassPathXmlApplicationContext時(shí)將Spring XML文件用作輸入類似,在實(shí)例化一個(gè)AnnotationConfigApplicationContext時(shí)可以使用@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構(gòu)造器的輸入。比如:
public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class);MyService myService = ctx.getBean(MyService.class);myService.doStuff(); }參考
轉(zhuǎn)載于:https://www.cnblogs.com/lawlietfans/p/7667518.html
總結(jié)
以上是生活随笔為你收集整理的如何在Spring和Spring MVC项目中进行测试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 1008 N的阶乘 mod P ——51
- 下一篇: 符号隔开数字求最大值