This test is invalid because server hasn't started yet when stopping it.
To Reproduce
Add fmt.Println("Started") before returing,like this:
func (s *Server) Start() error {
if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
return errors.New("a gRPC server can only be started once")
}
fmt.Println("Started")
return s.grpcServer.Serve(s.listener)
}
And add code fmt.Println("Stopped") after err := server.Stop() in func stopTestServer(t *testing.T, server *Server),
like this:
I stop grpc.Service twice, and panic occurred.
When I read service's unit test codes, I find the question:
This test is invalid because server hasn't started yet when stopping it.
To Reproduce Add
fmt.Println("Started")
before returing,like this:And add code
fmt.Println("Stopped")
aftererr := server.Stop()
infunc stopTestServer(t *testing.T, server *Server)
, like this:Run this test again, output:
This is an error test. To correcte it, add
time.Sleep(time.Second)
to last line ofstartTestServer
to ensure server has started:Run this test again, output:
Now write another test for stopping server twice:
Run it:
Alter calling
Stop()
firstly,s.grpcServer = nil
. When callingStop()
again,s.grpcServer.Stop()
will panic.How to resolve it ?
If we remove
s.grpcServer = nil
fromStop()
, the error will not occur, but codes from grpc will run every time, that's not a good thing.We can add
stopped
field to indicate if the server has stop.Expected behavior