Skip to content
This repository was archived by the owner on Sep 1, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ that is named `ping` and returns no content with 200 status.
}
```

4. Use [golangci-lint](https://github.com/golangci/golangci-lint) to lint your code :rocket:
5. Write tests for your endpoints. In the tests you must use MongoDB and check your recently created record.

For conntecting to Mongodb use the offical driver that can be found [here](https://github.com/mongodb/mongo-go-driver).
46 changes: 46 additions & 0 deletions newserver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package testing101
import(
"bytes"
"testing"
"net/http"
"github.com/labstack/echo"
"net/http/httptest"
)
func TestPinging(t *testing.T) {
e := echo.New()
e.GET("/ping",Pinging)
req, err := http.NewRequest("GET", "/ping", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
e.ServeHTTP(rr, req)
status := rr.Code
if status != http.StatusOK {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use tesify library for assertion in tests. Use assertion makes your test automatic.

t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
if status == http.StatusOK {
t.Errorf("handler returned expected body: got %v with status %v",rr.Body.String(),status)
}
}
func TestPosting(t *testing.T){
e := echo.New()
e.POST("/posting",JsonHandler)
var jsonStr = []byte(`{"lat":"20ms","lng":"english"}`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to have two separate tests for valid and invalid data that return different status codes.

req, err := http.NewRequest("POST", "/posting", bytes.NewBuffer(jsonStr))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
e.ServeHTTP(rr, req)
status := rr.Code
if status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status,http.StatusOK)
}
if status == http.StatusOK {
t.Errorf("handler returned expected body: got %v with status %v",rr.Body.String(),status)
}
}