SpringBoot学习笔记4 - 单元测试与自定义异常页面

tech2026-03-30  4

1、创建单元测试


创建测试Service接口及其实现类:

public interface DemoService { String hello(); } @Service public class DemoServiceImpl implements DemoService { @Override public String hello() { return "Hello Junit Test!"; } }

添加测试类与测试方法

package com.blairscott; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { @Autowired private DemoService demoService; @Test public void contextLoads() { System.out.println(demoService.hello()); } }

结果显示

2、自定义异常界面


假设在上一实例中发生了异常,如我们定义一个Controller类:

@RestController public class HelloController { @Autowired private DemoService service; @GetMapping("/demo") public String sayHello() { int i = 1 / 0; // 这一步一定会出现异常 return service.hello(); } }

启动Application.java中的main方法后,显示结果:

显然,诸如505、404等这样系统级异常,将这样的结果返回给用户是不合理的,此时我们可以解析各类错误结果,并以对用户友好的方式呈现给用户:

在resources目录下创建public/error目录 注意:resources资源目录下添加目录,多级目录之间要用“/”分割,而不能用“.”,否则就会创建一个名为public.error的文件夹。

创建并编辑异常页面 注意:修改404界面则创建404.html,修改500界面则创建500.html。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 服务器异常,请联系管理员! </body> </html>

通过程序异常访问该异常界面

最新回复(0)