Testing constructors

agolangf · · 543 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi,</p> <p>I have a constructor like this:</p> <pre><code>package busybus import ( &#34;bufio&#34; &#34;net&#34; ) type Client struct { counter integer conn net.Conn bufin *bufio.Reader bufout *bufio.Writer messages chan string state string } func NewClient(conn net.Conn, messages chan string) *Client { return &amp;Client{ counter: 0, conn: conn, bufin: bufio.NewReader(conn), bufout: bufio.NewWriter(conn), messages: messages, state: &#34;waiting&#34;, } } </code></pre> <p>How I can test the Client instance I get from this constructor has the fields I&#39;m expecting ?</p> <p>For example:</p> <pre><code>package busybus import ( &#34;fmt&#34; &#34;net&#34; &#34;testing&#34; ) func TestNewClient(t *testing.T) { ln, _ := net.Listen(&#34;tcp&#34;, &#34;:65535&#34;) fmt.Println(&#34;a&#34;) conn, _ := ln.Accept() fmt.Println(&#34;a&#34;) messages := make(chan string) client := NewClient(conn, messages) if client.conn != conn { t.Errorf(&#34;NewClient(%q, %q).conn == %q, want %q&#34;, conn, messages, client.conn, conn) } } </code></pre> <p>this hangs during test run due to ln.Accept() and seems simply wrong, what are your suggestion to test it ?</p> <hr/>**评论:**<br/><br/>nesigma: <pre><p>How about:</p> <pre><code>package busybus import ( &#34;bufio&#34; &#34;net&#34; &#34;reflect&#34; &#34;testing&#34; ) func TestNewClient(t *testing.T) { conn := &amp;net.IPConn{} messages := make(chan string) want := &amp;Client{ counter: 0, conn: conn, bufin: bufio.NewReader(conn), bufout: bufio.NewWriter(conn), messages: messages, state: &#34;waiting&#34;, } got := NewClient(conn, messages) if !reflect.DeepEqual(got, want) { t.Errorf(&#34;NewClient(%q, %q).conn == %q, want %q&#34;, conn, messages, got, want) } } </code></pre> <p>P.S. I am assuming it is &#34;counter int&#34; and not &#34;counter integer&#34;.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

543 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传