Spring integrated JUnit for unit testing and common exception resolution

Source: Internet
Author: User

Spring-test Dependency Packages

<!--spring-test -<!--https://mvnrepository.com/artifact/org.springframework/spring-test -<Dependency>    <groupId>Org.springframework</groupId>    <Artifactid>Spring-test</Artifactid>    <version>4.3.7.RELEASE</version></Dependency>

1. Simple Unit Test

 Packagecom.ssm.test;Importjava.util.List;ImportJava.util.Map;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportCom.ssm.dao.UserMngDao;/**  * @authorWangxiangyu * @date: July 18, 2017 2:24:50 * Class Description: Spring unit Test * 1, Import spring-test Unit Test jar Package * 2, @ContextConfiguration (Loca tions={"Classpath:applicationContext.xml"}) specifies the location of the spring configuration file * 3, @RunWith (Springjunit4classrunner.class) Using Spring Unit Test * 3, directly autowired the components to be used*/@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations={"Classpath:applicationContext.xml"}) Public classmappertest {@Autowired Usermngdao Usermngdao; @Test Public voidtest1 () {List<Map> users =Usermngdao.findall ();  for(Map user:users) {String staffname=NULL==user.get ("Staffname")? "": User.get ("Staffname"). toString ();        System.out.println (Staffname); }            }}

2. Analog front-end request Unit test

 Packagecom.atguigu.crud.test;Importjava.util.List;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.mock.web.MockHttpServletRequest;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Importorg.springframework.test.context.web.WebAppConfiguration;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;ImportOrg.springframework.test.web.servlet.MvcResult;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;ImportOrg.springframework.web.context.WebApplicationContext;ImportCom.atguigu.crud.bean.Employee;ImportCom.github.pagehelper.PageInfo;/*** Use the test request function provided by the Spring Test module to test the correctness of the curd request * SPRING4 Test requires servlet3.0 support *@authorLfy **/@RunWith (Springjunit4classrunner.class) @WebAppConfiguration @contextconfiguration (Locations= {"Classpath:applicationContext.xml", "File:src/main/webapp/web-inf/dispatcherservlet-servlet.xml" }) Public classMvctest {//the IOC passed into the SPRINGMVC@Autowired Webapplicationcontext context; //virtual MVC request, gets to the processing result. Mockmvc Mockmvc; @Before Public voidInitmokcmvc () {MOCKMVC=Mockmvcbuilders.webappcontextsetup (context). build (); } @Test Public voidTestpage ()throwsException {//The impersonation request gets the return valueMvcresult result = Mockmvc.perform (Mockmvcrequestbuilders.get ("/emps"). Param ("pn", "5") . Andreturn (); //after the request succeeds, there will be pageinfo in the request domain; we can remove the PageInfo for verification.Mockhttpservletrequest request =result.getrequest (); PageInfo Pi= (PageInfo) request.getattribute ("PageInfo"); System.out.println ("Current page number:" +pi.getpagenum ()); System.out.println ("Total page number:" +pi.getpages ()); System.out.println ("Total Records:" +pi.gettotal ()); System.out.println ("Page numbers that need to be displayed continuously in the pages"); int[] Nums =pi.getnavigatepagenums ();  for(inti:nums) {System.out.print (" "+i); }                //Get Employee Datalist<employee> list =pi.getlist ();  for(Employee employee:list) {System.out.println ("ID:" +employee.getempid () + "==>name:" +employee.getempname ()); }            }}

3. JUnit Common anomalies and solutions

Abnormal:
java.lang.IllegalStateException:Failed to load ApplicationContext

Workaround:
The java1.8 version only supports spring4.0 or more. So there are two ways to solve the problem: 1) Change the sping version to 4.0 or more, 2) lower the JDK. Here I choose to lower the JDK and run it again.

Abnormal:
Java.lang.noclassdeffounderror:org/junit/runners/model/multiplefailureexception

Workaround:
There is no multiplefailureexception class, it may be because your version is too low, please replace the latest version.

Abnormal:
Java.lang.Exception:No tests found matching [{Exactmatcher:fdisplayname=test_sayhello4]

Workaround:
Spring-test version is incompatible with the JUnit version, you can try several more versions.

Spring integrated JUnit for unit testing and common exception resolution

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.