`

sprintboot-第四章SpringBoot2.0单元测试进阶实战和自定义异常处理

 
阅读更多
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AutogenprojectApplication.class)
public class AutogenprojectApplicationTests {

   @Test
public void test1() {
      System.out.println("1");
      TestCase.assertEquals(1,0);
   }
   @Test
public void test2() {
      System.out.println("2");
      TestCase.assertEquals(1,1);
   }
   @Before
public void testA()
   {
      System.out.println("before");
   }
   @After
public void testB()
   {
      System.out.println("After");
   }

 

MockMvc测试

perform:执行一个RequestBuilder请求

andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则

andReturn:最后返回相应的MvcResult->Response

public class MockMVCTest {

    @Autowired
private MockMvc mockMvc;
    @Test
public void test1 () throws Exception
    {
            MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/a/a")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
            TestCase.assertEquals(mvcResult.getResponse().getStatus(),200);

    }
}

 banner修改,在classpath的根目录下添加一个banner.txt的文件即可不需要配置application.properties,如果是其他名子需要在application.properties中增加配置spring.banner.location=banner1.txt

banner1.txt的内容如下:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::你是我的小苹果(v2.1.3.RELEASE)

 

以debug的形式启动应用 java -jar xxx.jar --debug

 

全局异常处理

 

@RestControllerAdvice
public class CustomerExtHanlder {
    private static final Logger LOG  = LoggerFactory.getLogger(CustomerExtHanlder.class);
    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(Exception e , HttpServletRequest request)
    {
        LOG.error("error:{},utl{}",e.getMessage(),request.getRequestURL());
        Map map = new HashMap();
        map.put("status",200);
        map.put("error",e.getMessage());
        map.put("url", request.getRequestURL());
        return map;
    }

    @ExceptionHandler(MyException.class)
    public Object exceptionHandler2(Exception e , HttpServletRequest request)
    {
        LOG.error("error:{},utl{}",e.getMessage(),request.getRequestURL());
        ModelAndView mav = new ModelAndView();
        mav.setViewName("error.html");
        mav.addObject("msg",e.getMessage());
        return mav;
    }
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics