Spring MVC unit Testing and integration testing (no mock)

Source: Internet
Author: User
Tags assert

Article Highlights:

1. Write test for controller, no application server environment required

2. Write tests for service, no application server environment required


Spring provides us with a test suite spring-test, which, in conjunction with JUnit, can launch the IOC container test service, the database, or the HTTP request test controller in an environment that is out of the Web container.

Test controller When we have finished writing a controller, the usual way to test is to deploy the application and then observe the effect of the run. If you want to write a test, you also need to mock the request parameters with mock objects, simulating httpsession, especially troublesome. Now Spring-test provides us with a more elegant way of testing. For example, to test the following controller:
@RequestMapping (value = {"/", "/shop"}, method = Requestmethod.get) public String Home () {return "index";}

The corresponding test code is:
@Testpublic void Testhome () throws Exception {Mockmvc mock = mockmvcbuilders.standalonesetup (HomeController). build (); Mock.perform (Get ("/")). Andexpect (Status (). IsOk ()). Andexpect (Forwardedurl ("index"));}

In the test code, we send a GET request "/" to HomeController, and then determine whether the HTTP status code (Andexpect () method) is 200, and then determine whether to jump to the "index" page. If there is an error in any loop, the test will fail. We can also transfer request parameters:
Mock.perform (Get ("/"). Param ("username", "password")). Andexpect (Status (). IsOk ());

Note that the ability to call get () directly is due to the use of static import:
Import static Org.springframework.test.web.servlet.request.mockmvcrequestbuilders.get;import static Org.springframework.test.web.servlet.result.mockmvcresultmatchers.forwardedurl;import Static Org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


The complete test code is as follows:
@RunWith (springjunit4classrunner.class) @ContextConfigurationpublic class Homecontrollertest {@Autowiredprivate HomeController homecontroller; @Testpublic void Testhome () throws Exception {Mockmvc mock = Mockmvcbuilders.standalonesetup (HomeController). build (); Mock.perform (Get ("/")). Andexpect (Status (). IsOk ()). Andexpect (Forwardedurl ("index"));}

The test Serviceservice method typically links to data operations, so it is difficult to test with junit alone. But spring-test can be easily addressed. JUnit gives spring the power to launch the IOC container by handing control over to spring with the @runwith annotation:
@RunWith (Springjunit4classrunner.class)

Such dependency injection can be used (@Autowired annotations). Before using it, however, to configure the bean, if it involves database operations, configure Localcontainerentitymanagerfactorybean, just as we did in web development. The database configuration bean is as follows:
/** * Database Test Configuration class * @author WHF * */@Configurationpublic class Databaseconfigure {@Autowiredprivate DataSource DataSource; @Au Towiredprivate entitymanagerfactory entitymanagerfactory, @Beanpublic factorybean<entitymanagerfactory> Entitymanagerfactory () {Localcontainerentitymanagerfactorybean EMFB = new Localcontainerentitymanagerfactorybean (); Emfb.setdatasource (This.datasource); Emfb.setjpavendoradapter (Jpavendoradapter ()); Emfb.setpackagestoscan (" Your package "); Properties prop = new properties ();p rop.put ("Hibernate.hbm2ddl.auto", "Create-drop");p rop.put ("Hibernate.show_sql", "true");p rop.put ("Hibernate.format_sql", "true");p rop.put ("Hibernate.dialect", "Org.hibernate.dialect.H2Dialect" ); emfb.setjpaproperties (prop); return EMFB;} @Beanpublic Jpavendoradapter Jpavendoradapter () {return new Hibernatejpavendoradapter ();} @Beanpublic Platformtransactionmanager TransactionManager () {Jpatransactionmanager Txmanager = new Jpatransactionmanager (); Txmanager.setentitymanagerfactory (This.entitymanagerfaCtory); Txmanager.setdatasource (This.datasource); return Txmanager;} @Beanpublic DataSource DataSource () {Embeddeddatabasebuilder builder = new Embeddeddatabasebuilder (); Builder.settype ( EMBEDDEDDATABASETYPE.H2); return Builder.build ();}}

So we can inject the entitymanager. A complete test code is as follows:
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (classes = {Databaseconfigure.class, Defaultaccountservice.class}) @TransactionConfiguration @transactional (readOnly = true) public class accountservicetest {@Autowiredprivate accountservice acservice; @PersistenceContextprivate Entitymanager em;private Member m; @Before @transactional (readOnly = false) public void Initaccountdata () {m = new Member (); M.setusername ("Bruce"); M.setpassword ("3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d"); Em.persist (m);} @After @transactional (readOnly = false) public void Cleandatabase () {m = Em.merge (m); Em.remove (m);} @Testpublic void Testfindbyusername () {Member m = Acservice.findmember ("Bruce"); Assert.assertnotnull (m); Assert.assertequals ("Bruce", M.getusername ()); Assert.assertequals ("3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d", M.getpassword ());}

With Spring-test, the time of server startup and application deployment is eliminated, which greatly improves the efficiency of development and also reduces the production of bugs. The Maven dependencies required to run the above test code are as follows:
<dependency><groupid>org.springframework</groupid><artifactid>spring-test</ Artifactid><version>${spring.version}</version></dependency>

<!--JDBC Connection pool--><dependency><groupid>commons-dbcp</groupid><artifactid> commons-dbcp</artifactid><version>1.4</version><scope>test</scope></ dependency><dependency><groupid>com.h2database</groupid><artifactid>h2</ Artifactid><version>1.4.182</version><scope>test</scope></dependency>


I wish you a good coding

Spring MVC unit Testing and integration testing (no mock)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.