dqys98341 2016-06-29 15:43
浏览 121
已采纳

Golang中的Stubb接口指针参数

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.

  • 写回答

1条回答 默认 最新

  • duanji1902 2016-06-29 15:53
    关注

    net.Conn is an interface. There is almost never a need to use a pointer to an interface, and you aren't going to find any functions that take a pointer to an interface.

    Use a net.Conn value in the map.

    conns map[int]net.Conn
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题