这是我的Globalexceptionhandlerclass.java。我试图编写JUnit 5测试用例,但遇到了问题。有人能帮我吗?
Globalexceptionhandlerclass.java
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
protected final Log loger = LogFactory.getLog(ResponseEntityExceptionHandler.class);
@ExceptionHandler(Exception.class)
ResponseEntity<?> handleAllExceptions(Exception ex, WebRequest request ) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("date", new Date());
result.put("message", ex.getMessage());
result.put("details", request.getDescription(true));
loger.error(ex);
ResponseEntity<?> responseEntity = ResponseEntity.badRequest()
.header("exception-erro", "error")
.body(result);
return responseEntity;
}
}
这是我的GlobalExceptionHandlerTest.java
。我陷入了困境,它正在失败。我尝试了其他方法,但没有效果。最后两行不行了,我不知道为什么。任何人都请帮我查一下这些案子。这对我很有帮助。
import javax.servlet.http.HttpServletRequest;
@ExtendWith(MockitoExtension.class)
class ExceptionHandlerControllerAdviceTest {
/**
* Given a handle invalid exception when controller advice then return a bad request exception.
*/
@Test
void handleInvalidFormatException() {
GlobalExceptionHandler controllerAdvice = new GlobalExceptionHandler();
ResponseEntity<?> response = controllerAdvice.handleAllExceptions(null, null);
assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatusCode().value());
}
}
handleAllExceptions
不是空安全的,因为这一行result.put("message", ex.getMessage());
和您在测试controllerAdvice.handleAllExceptions(null, null)
中传递了具有空值的ex
。
这个测试没有任何理由,因为Spring总是为您提供Exception和WebRequest。因此,在Spring环境中调用handleAllExceptions(null, null)
是不可能的。