Golang中Stubb接口指针参数
Stubb interface pointer parameters in Golang
假设我有一个将客户端 ID 映射到 net.Conns(接口)的存储。为了简单起见,它只是在其中隐藏了一个地图并将地图键作为参数。
我想消除对值复制的需要,我来自 Java 的土地,所以映射应该将 id 映射到 net.Conn 指针似乎合乎逻辑。
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.
现在我想为代码编写自动测试,但没有实际的 Conns,所以我编写了自己的 StubbConn 和 Stubb 所有 net.Conn 接口方法。
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..
然后我尝试在测试中使用这个 StubbConn...
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")
}
}
导致编译错误:
cannot use conn (type *StubConn) as type *net.Conn in argument to clients.Add:
*net.Conn is pointer to interface, not interface
但是如果 add 函数将参数作为 conn net.Conn
(值)并使地图保存值,它就会起作用。所以看起来即使 Stubb 接口,Stubb 指针也不会作为指向真实接口的指针传递。
有没有办法将我的 StubbConn 指针作为指向 Conn 的指针传递给将指向接口的指针作为参数的函数?
即使我完全迷失了并且应该让我的地图保存实际的 Conn 值而不是指针(如果我应该这样做请告诉我),问题仍然是单元测试其他函数指向接口的指针作为参数。
net.Conn
是一个接口。几乎从不需要使用指向接口的指针,并且您不会找到任何采用指向接口的指针的函数。
在地图中使用 net.Conn
值。
conns map[int]net.Conn
假设我有一个将客户端 ID 映射到 net.Conns(接口)的存储。为了简单起见,它只是在其中隐藏了一个地图并将地图键作为参数。
我想消除对值复制的需要,我来自 Java 的土地,所以映射应该将 id 映射到 net.Conn 指针似乎合乎逻辑。
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.
现在我想为代码编写自动测试,但没有实际的 Conns,所以我编写了自己的 StubbConn 和 Stubb 所有 net.Conn 接口方法。
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..
然后我尝试在测试中使用这个 StubbConn...
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")
}
}
导致编译错误:
cannot use conn (type *StubConn) as type *net.Conn in argument to clients.Add:
*net.Conn is pointer to interface, not interface
但是如果 add 函数将参数作为 conn net.Conn
(值)并使地图保存值,它就会起作用。所以看起来即使 Stubb 接口,Stubb 指针也不会作为指向真实接口的指针传递。
有没有办法将我的 StubbConn 指针作为指向 Conn 的指针传递给将指向接口的指针作为参数的函数?
即使我完全迷失了并且应该让我的地图保存实际的 Conn 值而不是指针(如果我应该这样做请告诉我),问题仍然是单元测试其他函数指向接口的指针作为参数。
net.Conn
是一个接口。几乎从不需要使用指向接口的指针,并且您不会找到任何采用指向接口的指针的函数。
在地图中使用 net.Conn
值。
conns map[int]net.Conn