Testing http ListenAndServe wrapper function

Hi,

Just wondering how I can test Start method below or should I actually test it? If I am to just call Start in my test, it hangs because I believe it actually starts the server which is something we want to avoid.

Thanks

package http

import (
	"net/http"
)

type Server struct {
	*http.Server
}

func NewServer(adr string) Server {
	return Server{
		&http.Server{
			Addr:    adr,
			Handler: nil,
		},
	}
}

func (s Server) Start() error {
	if err := s.ListenAndServe(); err != http.ErrServerClosed {
		return err
	}

	return nil
}
func TestServer_Start(t *testing.T) {
	// ???
}
2 Likes

The test function could start a go routine that calls Shutdown after a 1 second sleep. This would allow you to call the Start function in your test. But do you really need to test such a simple function ?

Here is an example code that will call Shutdown and stop the server after 1 second.

func TestServer_Start(t *testing.T) {
	srv := NewServer(":45566")
	go func () {
		time.Sleep(1*time.Second)
		srv.Shutdown(context.Background())
	}()
	err := srv.Start()
	if err != nil {
		t.Error("unexpected error:", err)
	}
}
3 Likes

Much appreciated @Christophe_Meessen. Helping this learner a lot.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.