Spring Boot全局异常JUnit测试:DelController未触发全局异常处理器
全局异常处理器未触发的问题解决
问题原因
直接通过@InjectMocks注入控制器后调用方法,属于普通Java方法调用,不会经过Spring MVC的请求处理流程,因此@ControllerAdvice标注的全局异常处理器不会被触发。全局异常处理器是由Spring的DispatcherServlet在处理请求时统一捕获并分发到对应的@ExceptionHandler方法的,直接调用控制器方法时这一机制不会生效。
解决方案
改用Spring MVC提供的MockMvc来模拟HTTP请求,这样就能完整触发Spring的请求处理流程,包括全局异常处理器的逻辑。
修改后的测试代码
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(DelController.class) public class ControllerTest { @Autowired private MockMvc mockMvc; @Test public void getTest() throws Exception { mockMvc.perform(get("/getId/{intakeNumber}", "123po")) .andExpect(status().isBadRequest()); } }
额外注意事项
- 确保
DelIntakeGlobalException是运行时异常(继承自RuntimeException),否则需要在控制器方法上声明抛出该异常:
public class DelIntakeGlobalException extends RuntimeException { public DelIntakeGlobalException(String message) { super(message); } }
- 修正原代码中的拼写错误:
@Runwith改为@RunWith,测试方法getTest添加返回类型void。
内容的提问来源于stack exchange,提问作者Iswarya Elango
相关产品推荐
相关产品推荐

