去模拟 postgresql 错误
Go Mock postgresql errors
正如本文 中所讨论的,我编写了用于检查唯一密钥违规的代码:
if err, ok := err.(*pq.Error); ok {
if err.Code.Name() == "unique_violation" {
fail(w, http.StatusBadRequest, 0, "Item already exists")
return
}
}
为了编写单元测试用例,我需要模拟这个错误。我已经为这样的错误编写了模拟:
return pq.Error{Code: "unique_violation"}
但这与代码不符。我如何模拟 pq.Error
?
如 Godoc, ErrorCode is a five-character error code.
err.Code.Name()
gets the human-friendly version of the error, but the error itself should be represented, and thus constructed, by the error code, which in this case is 23505 中所述。
正如本文
if err, ok := err.(*pq.Error); ok {
if err.Code.Name() == "unique_violation" {
fail(w, http.StatusBadRequest, 0, "Item already exists")
return
}
}
为了编写单元测试用例,我需要模拟这个错误。我已经为这样的错误编写了模拟:
return pq.Error{Code: "unique_violation"}
但这与代码不符。我如何模拟 pq.Error
?
如 Godoc, ErrorCode is a five-character error code.
err.Code.Name()
gets the human-friendly version of the error, but the error itself should be represented, and thus constructed, by the error code, which in this case is 23505 中所述。