0

I am trying to write unit test for my app. I am using fasthttp lib. I also use fasthttp-routing lib. So the problem is that my handler is not standard type of fasthttp.HandlerFunc but routing.Handler.

In order to test HTTP handlers i've written the function that accepts handler fasthttp.RequestHandler parameter. The lib method fasthttp.Serve() accepts handler with type fasthttp.RequestHandler. I use this method to serve incoming connections from the given listener using the given handler. But my handler is of type routing.Handler

My handler:

func deleteExampleBOById(c *routing.Context) error { // Some logic }

My serve() function that i use to serve connections in order to unit test handlers:

func serve(handler fasthttp.RequestHandler, req *http.Request) (*http.Response, error) {
    ln := fasthttputil.NewInmemoryListener()
    defer ln.Close()

    go func() {
        err := fasthttp.Serve(ln, handler)
        if err != nil {
            panic(fmt.Errorf("failed to serve: %v", err))
        }
    }()

    client := http.Client{
        Transport: &http.Transport{
            DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
                return ln.Dial()
            },
        },
    }

    return client.Do(req)
}

My actual unit test:

func TestHandler(t *testing.T) {
    r, err := http.NewRequest("GET", "http://localhost:8181/GoService/example/v1/1", nil)
    if err != nil {
        t.Error(err)
    }

    res, err := serve(getExampleBOById, r)
    if err != nil {
        t.Error(err)
    }

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Error(err)
    }

    fmt.Println(string(body))
}

I am not able to serve my handler using function fasthttp.serve(), because of signature differences. I would like to ask any ideas how to convert routung.Handler to fasthttp.HandlerFunc or any other ideas how to unit test my handlers.

I don't have ideas how to solve it

Amin Rashidbeigi
  • 670
  • 6
  • 11

0 Answers0