These are chat archives for gin-gonic/gin

6th
Jun 2016
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:40
hi,everyone.
how do i unit test my codes while using gin-gonic?
Ousmane Traore
@otraore
Jun 06 2016 02:41
One second
I’ve answered this before :p
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:42
:smile:
Ousmane Traore
@otraore
Jun 06 2016 02:42
@tboerger Testing gin controllers isn't hard, but you're right finding examples is a bit difficult Here's one to get you started: http://play.golang.org/p/qyhD0mlCST, I was actually frustrated at first but once you get up and running, tests become a breeze.
I personally use github.com/smartystreets/goconvey/convey so my tests look something like this:
func TestUsersResource(t *testing.T) {
    r := controllers.Router() //Insert your router here
    Convey("Empty POST request to /users should return Bad Request", t, func() {
        req, _ := http.NewRequest("POST", "/users", nil)
        resp := httptest.NewRecorder()
        r.ServeHTTP(resp, req)
        So(resp.Code, ShouldEqual, http.StatusBadRequest)
    })
    ...
}
Check out the go playground one too if you don’t want to use goconvey and like draditional tests
with testify/assert
Hope that answers your question :D
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:49
nice! i think this code snippet should be added into https://github.com/gin-gonic/gin/blob/develop/README.md
Ousmane Traore
@otraore
Jun 06 2016 02:50
Now that you mention it, it is commonly asked
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:50
when i try to decide which framework to use, easy to test codes really matters.
Ousmane Traore
@otraore
Jun 06 2016 02:50
As much as I love goconvey
I think the testify/assert one would be more general
But I personally love my test suite
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:51
yeah,assert is my preferred one by now
Ousmane Traore
@otraore
Jun 06 2016 02:51
yeah I use it at times
Bruce Auyeung
@bruceauyeung
Jun 06 2016 02:51
assert is more java-like.
Ousmane Traore
@otraore
Jun 06 2016 02:51
but for one of my API projects goconvey won me over
And the UI is nice
But the tests describe themselves
I think they make more sense for integration tests rather than unit tests
Bruce Auyeung
@bruceauyeung
Jun 06 2016 03:04
@otraore does goconvey have mock mechanism?