mercredi 29 juin 2016

Stubb interface pointer parameters in Golang

Say that I have a Storage which maps client id's to net.Conns (interface). For the sake of simplicity, it's just hides a map inside it and gets map key as a parameter.

I want to eliminate the need for value copying, and I come from the land of Java, so it seems logical that the map should map id's to net.Conn pointers.

type Storage struct {
     conns map[int]*net.Conn
}

func (s *Storage) Add(id int, conn *net.Conn){
   s.conns[id] = conn
}

... methods for initialising new storage, getting, deleting, 
maybe giving list of user id's etc.

Now I want to write automatic tests for the code, but without actual Conns, so I write my own StubbConn and Stubb all the net.Conn -interface methods.

type StubConn struct{}

func (s *StubConn) Read(b []byte) (n int, err error)   { return 0, nil }
func (s *StubConn) Write(b []byte) (n int, err error)  { return 0, nil }
etc..

And then I try to use this StubbConn in testing...

func TestAddOneClient(t *testing.T) {
    clients := GetStorage()
    conn := new(StubConn)
    clients.Add(5, conn)
    if len(clients.conns) != 1 {
        t.Error("Expected client adding to increment storage map size")
    }
}

It results in compilation error:

cannot use conn (type *StubConn) as type *net.Conn in argument to clients.Add:
*net.Conn is pointer to interface, not interface

But it works if the add function takes parameters as conn net.Conn (values) and make the map hold values instead. So it seems that even if Stubb the interface, the Stubb pointer isn't going to pass as a pointer to the real interface.

Is there a way to pass my StubbConn pointer acting as a pointer to Conn for functions that take pointer to an interface as a parameter?

Even if I'm completely lost and should chance my map to hold actual Conn-values instead of pointers (and please do tell me if I should be doing that), the question holds for unit testing other functions that take pointers to interfaces as params.

Aucun commentaire:

Enregistrer un commentaire