1

I have two questions on this go swagger generated codes, firstly I made my first api with go swagger but my employer asked me to implement the unit (go test) but trying to perform the usual http test does not work, here is my test code bellow

// handlers_test.go
package handlers

import (
    "net/http"
    "net/http/httptest"
    "testing"
    "StocksApp/restapi/operations"
)

func TestStockHandler(t *testing.T) {
    // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
    // pass 'nil' as the third parameter.
    req, err := http.NewRequest("GET", "/api/v1/stocks", nil)
    if err != nil {
        t.Fatal(err)
    }

    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(operations.StocksHandler)

    // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
    // directly and pass in our Request and ResponseRecorder.
    handler.ServeHTTP(rr, req)

    // Check the status code is what we expect.
    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    expected := `{"alive": true}`
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

but I am getting this error and I don't know how to solve it

# StocksApp/handlers [StocksApp/handlers.test]
.\handlers_test.go:21:32: type operations.StocksHandler is not an expression
FAIL    StocksApp/handlers [build failed]

secondly, when ever i run the go run main.go command, the server runs in a different port, i will like to know how I can hardcode a permanent port number that the server will always run on

  • Wihtout your actual handlers file its hard to produce the fix. In your test file `operations.StocksHandler` is the issue. This is not an expression (as the error suggests). Is this a dependency you need to setup or mock? – metalisticpain Sep 30 '21 at 16:18
  • Isn't stocksHandler a method? Not sure but might be the case you have to invoke the function. – Marco Oct 22 '21 at 07:21

1 Answers1

0

You can use HandlerFor method to get valid http.Handler for your operation. See an example on: https://github.com/go-swagger/go-swagger/blob/master/examples/generated/restapi/operations/petstore_api.go#L436

serge-v
  • 750
  • 2
  • 8