Mainly record the test of the controller, service these classes of tests are relatively simple (testability)
API testing requirements are relatively straightforward:
① need to return the correct HTTP status Code 200
② needs to return JSON data and cannot return an uncaught system exception
Test does not pass an example
Part of the code for this test class
PackageCn.taxiong.search.web.controller;Importcn.taxiong.search.Application;ImportCn.taxiong.search.constant.ErrorCodeMsgEnum;Importorg.hamcrest.Matchers;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.http.MediaType;ImportOrg.springframework.test.context.junit4.SpringRunner;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;ImportOrg.springframework.web.context.WebApplicationContext;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultHandlers.print;Import Staticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; the @RunWith (Springrunner.class) @SpringBootTest (Classes= Application.class, webenvironment =SpringBootTest.WebEnvironment.RANDOM_PORT) Public classSearchcontrollertest {PrivateMockmvc Mockmvc; @AutowiredprotectedWebapplicationcontext WAC; @Before ()//This method executes all the way before each method executes . Public voidSetup () {Mockmvc= Mockmvcbuilders.webappcontextsetup (WAC). build ();//initializing the Mockmvc object} @Test Public voidShopsearch ()throwsException {mockmvc.perform (Mockmvcrequestbuilders.get ("/shopsearch"). Accept (Mediatype.application_json_utf8). Param ("Page", "1"). param ("PageSize", "2"). param ("StartDate", "2018-01-01"). param ("EndDate", "2028-01-01"). param ("Keyword", "Jiao chang Tail"). param ("Lat", "22.22"). param ("Lon", "42.22"). param ("Distance", "5000"). param ("Capacity", "2"). param ("Style", "3"). param ("GT", "1"). param ("LT", "9900"). param ("Keywordscope", "0"). param ("Sort", "DEFAULT"). param ("Service", "{6,7}"). param ("Facilities", "{5,6}"). param ("Shoptype", "1"). param ("Goodscategory", "1") . Andexpect (Status (). IsOk ())//To determine the return status. Andexpect (Content (). ContentType ("Application/json;charset=utf-8"))//Determine content Type. Andexpect (JsonPath ("$.code", Matchers.not (ErrorCodeMsgEnum.SYSTEM_ERROR.getCode ())))//if it is a system exception (an uncaught exception), the test does not pass. Anddo (print ());//print out the request and the corresponding content }}
Test Pass Examples:
Springboot using MOCKMVC to test controller controllers