Unit Testing with Go-Chi/Chi

Viewed 1831

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?

0 Answers
Related