3

I am trying to write unit tests for my rest endpoints using Go-Chi as my mux.

Previously I was using gorilla/mux but moved to Chi because it is easier to maintain as my application grows.

With Gorilla/mux, I was able to use "ServeHTTP" to send a test request but using go-chi/chi it does not seem to do the same thing.

var writer *httptest.ResponseRecorder
var r = chi.Mux{}

func TestMain(m *testing.M) {
    setUp()
    code := m.Run()
    os.Exit(code)
}

func setUp() {
    d, _ := database.ConnectToDB(database.TESTDBNAME)
    writer = httptest.NewRecorder()
    r := chi.NewMux()
    r.Route("/companies", func(r chi.Router) {
        r.Get("/", GetCompanies(d))
        r.Get("/{id}", GetCompany(d))
        r.Post("/", PostCompany(d))
        r.Put("/{id}", PutCompany(d))
        r.Delete("/{id}", DeleteCompany(d))
    })
}

func TestPostCompany(t *testing.T) {
    tables := []struct {
        company   model.Company
        result int
    }{
        {model.Company{Name:"Test"}, 200},
    }

    for _, table := range tables {
        company, err := json.Marshal(table.company)
        if err != nil {
            t.Errorf("JSON Error")
        }
        companyJson := strings.NewReader(string(company))
        request, err := http.NewRequest("POST", "/companies", companyJson)
        if err != nil {
            t.Error(err)
        }
        r.ServeHTTP(writer, request)
        if writer.Code != table.result {
        t.Error(writer.Body)
        }
    }
}

Right now the test is showing a 404 error but I would like it to give a 200 error. This request works fine while running my application and testing manually.

I believe the issue has something to do with "ServeHTTP". Maybe it works differently with chi. Does anyone know how to get this test to run successfully?

jmacnc
  • 157
  • 2
  • 7
  • 19
  • 7
    Save yourself some trouble and just plug your production router into a `httptest.Server`. You're not testing your real setup if you're manually configuring the endpoints like this in your tests, instead of using your production configuration. – Crowman Jun 22 '19 at 00:08
  • 4
    Save yourself some further trouble and mock the database. Unitests ("given I get proper responses from the database, does _my_ code give the expected results") != integration tests ("given a known query, do I get the expected results from the database, does my code behave well on connection problems etc.") – Markus W Mahlberg Jun 22 '19 at 14:01
  • Save yourself a bit of trouble, after addressing the above comments, by taking a look at [my post](https://stackoverflow.com/a/70719412/5431797) which might be related to this . – Cabrera Jan 15 '22 at 06:51

0 Answers0