Importjava.awt.print.Printable; Importjava.io.IOException; ImportJavax.servlet.http.HttpServletResponse; ImportOrg.junit.Before; Importorg.junit.Test; ImportOrg.junit.runner.RunWith; Importorg.springframework.beans.factory.annotation.Autowired; ImportOrg.springframework.http.MediaType; 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.ResultHandler; ImportOrg.springframework.test.web.servlet.ResultMatcher; ImportOrg.springframework.ui.Model; Importorg.springframework.test.context.transaction.TransactionConfiguration; Importorg.springframework.transaction.annotation.Transactional; Import Staticorg.springframework.test.web.servlet.result.mockmvcresulthandlers.*; Import Staticorg.springframework.test.web.servlet.setup.mockmvcbuilders.*; Import Staticorg.springframework.test.web.servlet.request.mockmvcrequestbuilders.*; Import Staticorg.springframework.test.web.servlet.result.mockmvcresultmatchers.*; Importorg.springframework.web.bind.annotation.RequestMapping; ImportOrg.springframework.web.bind.annotation.RequestMethod; ImportOrg.springframework.web.context.WebApplicationContext; @RunWith (Springjunit4classrunner.class) @WebAppConfiguration @ContextConfiguration (Locations= {"Classpath:applicationContext.xml" }) //of course, you can declare that a transaction manages each unit test to perform a transaction rollback, whether successful or not@TransactionConfiguration (Defaultrollback =true) //Remember to declare the transaction in the XML file Oh ~ ~ ~ I'm using annotations@Transactional Public classexampletests {@AutowiredPrivateWebapplicationcontext WAC; PrivateMockmvc Mockmvc; @Before Public voidSetup () {//Webappcontextsetup Notice the static import above//Webappcontextsetup constructs a Web container that can add fileter but cannot add Listenclass//Webapplicationcontext context =//Contextloader.getcurrentwebapplicationcontext (); //If the controller contains the method above, it will report a null pointer This. Mockmvc = Webappcontextsetup ( This. WAC). build (); } @Test//Some unit tests you don't want to roll back@Rollback (false) Public voidownerID ()throwsException {mockmvc.perform (Get ("/spring/rest/4.do")) . Andexpect (Status (). IsOk ()). Anddo (print ()); } @Test Public voidTest ()throwsException {mockmvc.perform (Get ("/spring/test.do")) . Andexpect (Status (). IsOk ()). Anddo (print ()). Andexpect (Model (). Attributehasnoerro RS ("Teacher")); } @Test Public voidTESTB ()throwsException {mockmvc.perform (Get ("/spring/testb.do")) . Andexpect (Status (). IsOk ()). Anddo (print ()); } @Test Public voidGetaccount ()throwsException {mockmvc.perform (post ("/spring/post.do"). PARAM ("abc", "Def"))) . Andexpect (Status (). IsOk ()). Anddo (print ()); } }
Spring MVC Unit Test Example