java测试不成功_java – 测试@NotNull时集成测试失败
我無法重現您的結果,但也許通過澄清一些事情可以更接近您的問題.
如果我在我的機器上執行你的curl命令(帶有一個額外的-v標志來獲取標題),我會收到一個客戶端錯誤,確切地說是409 Conflict.
curl -v -H "Content-Type: application/json" -X POST -d '{}' http://localhost:8080/api/hotels
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /api/hotels HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 2
>
* upload completely sent off: 2 out of 2 bytes
< HTTP/1.1 409 Conflict
< Date: Sun, 22 Jan 2017 12:29:45 GMT
< Content-Type: application/hal+json;charset=UTF-8
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"cause":{"cause":{"cause":null,"message":"NULL not allowed for column \"ADDRESS\"; SQL statement:\ninsert into hotel (id, address, city_id, name, zip) values (null, ?, ?, ?, ?) [23502-193]"},"message":"could not execute statement"},"message":"could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"}
在我的IDE(STS)中執行測試也是如此:
java.lang.AssertionError: Range for response status value 409 expected: but was:
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$7.match(StatusResultMatchers.java:132)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
...
因此,首先測試和正在運行的應用程序之間沒有區別,DataIntegrityViolationException / ConstraintViolationException在兩種情況下都映射到409.
如果這是正確的另一個問題,但可能發送錯誤/無效數據實際上是客戶端錯誤.
如果您仍想更改它,則必須以這樣的方式添加自己的ExceptionHandler:
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity handleConstraintViolationException(Exception ex, WebRequest request) {
return handleExceptionInternal(ex, "I think it's the servers fault!", new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}
也許這可以解決你的問題,resp.給你一個提示.或者還有另一個我沒有得到的問題?
總結
以上是生活随笔為你收集整理的java测试不成功_java – 测试@NotNull时集成测试失败的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iqoo电池寿命长不长
- 下一篇: 超进化物语颜值增加有什么用