Unit tests, Global exceptions
One, unit test1. Basic version
1, the introduction of relevant dependencies
<!--springboot Program Test dependent, if it is automatically created project default add -<Dependency><groupId>Org.springframework.boot</groupId><Artifactid>Spring-boot-starter-test</Artifactid><Scope>Test</Scope></Dependency>
2: Key Note:@RunWith @SpringBootTest
Importjunit.framework.TestCase;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner; @RunWith (Springrunner.class)//The ground floor with JUnit Springjunit4classrunner@SpringBootTest(Classes={springbootstudyapplication.class})//start the entire Springboot project Public classSpringboottestdemo { @Test Public voidTestone () {System.out.println ("Test Hello 1"); Testcase.assertequals (1, 1); } @Test Public voidTesttwo () {System.out.println ("Test Hello 2"); Testcase.assertequals (1, 1); } @Before Public voidTestbefore () {System.out.println ("Before"); } @After Public voidTestafter () {System.out.println ("After"); } }
Output Result:
2.MOCKMVC
Use of the Mockmvc class and simulated HTTP request combat
TestController
Import org.springframework.web.bind.annotation.RequestMapping; Import Org.springframework.web.bind.annotation.RestController; @RestController Public class TestController { @RequestMapping ("/vq/test") public String gettest () { return"I am the Test return value"; }}
Mockmvctestdemo
Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;ImportORG.SPRINGFRAMEWORK.BOOT.TEST.AUTOCONFIGURE.WEB.SERVLET.AUTOCONFIGUREMOCKMVC;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;ImportOrg.springframework.test.web.servlet.MvcResult;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;/*** Function Description: Test MOCKMVC class **/@RunWith (Springrunner.class)//The ground floor with JUnit Springjunit4classrunner@SpringBootTest (classes={springbootstudyapplication.class})//start the entire Springboot project@AutoConfigureMockMvc Public classMockmvctestdemo {@AutowiredPrivateMockmvc Mockmvc; @Test Public voidApitest ()throwsException {mvcresult Mvcresult= Mockmvc.perform (Mockmvcrequestbuilders.get ("/vq/test") ). Andexpect (Mockmvcresultmatchers.status (). IsOk ()). Andreturn (); intStatus =mvcresult.getresponse (). GetStatus (); SYSTEM.OUT.PRINTLN (status); }}
Result: 200 status code returned
Summary, Key notes:
@RunWith (Springrunner.class) Lower layer with JUnit springjunit4classrunner@SpringBootTest(Classes={springbootstudyapplication.class})// Start the entire Springboot project
Second, configure global exceptions
First, it is unfriendly to springboot the exception.
Example
@RequestMapping (value = "/api/v1/test_ext") Public Object Index () { int i= 1/0; return New New Date ()); }
page
1. Configuring Global Exceptions
ImportJava.util.HashMap;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.springframework.web.bind.annotation.ExceptionHandler;ImportOrg.springframework.web.bind.annotation.RestControllerAdvice; //Add global exception annotations @RestControllerAdvice Public classCustomexthandler {Private Static FinalLogger LOG = Loggerfactory.getlogger (Customexthandler.class); //captures global exceptions and handles all unknown exceptions @ExceptionHandler(Value=exception.class) //@ResponseBodyObject handleexception (Exception e,httpservletrequest request) {Log.error ("URL {}, msg {}", Request.getrequesturl (), E.getmessage ()); Map<string, object> map =NewHashmap<>(); Map.put ("Code", 100); Map.put ("MSG", E.getmessage ()); Map.put ("url", Request.getrequesturl ()); returnmap; } }
look at the page:
Key notes:
@RestControllerAdvice //Global annotations
@ExceptionHandler(Value=exception.class) //Catch different exceptions, where catch is Exception exception, you can also specify other exceptions
2. Custom Exceptions
In Java, you can customize exceptions. Here are some things to keep in mind when writing your own exception classes.
- All exceptions must be subclasses of Throwable .
- If you want to write an inspection exception class, you need to inherit the Exception class.
- If you want to write a run-time exception class, you need to inherit the RuntimeException class.
1. Custom myexception exceptions
/*** Function Description: Custom Exception class **/ Public classMyExceptionextendsRuntimeException {Private Static Final LongSerialversionuid = 1L; Publicmyexception (string code, String msg) { This. Code =Code; This. msg =msg; } PrivateString Code; PrivateString msg; PublicString GetCode () {returnCode; } Public voidSetcode (String code) { This. Code =Code; } PublicString getmsg () {returnmsg; } Public voidsetmsg (String msg) { This. msg =msg; }}
Controller class
/** * Function Description: Simulate custom exception * /@RequestMapping ("/api/v1/myext") Public Object Myexc () { //throws an exception directly throw the new myexception ("499", "my Ext exception "); }
Page
Think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Captain "7"
Springboot (5)---Unit test, global exception