<p>Hi,</p>
<p>I have a constructor like this:</p>
<pre><code>package busybus
import (
"bufio"
"net"
)
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 &Client{
counter: 0,
conn: conn,
bufin: bufio.NewReader(conn),
bufout: bufio.NewWriter(conn),
messages: messages,
state: "waiting",
}
}
</code></pre>
<p>How I can test the Client instance I get from this constructor has the fields I'm expecting ?</p>
<p>For example:</p>
<pre><code>package busybus
import (
"fmt"
"net"
"testing"
)
func TestNewClient(t *testing.T) {
ln, _ := net.Listen("tcp", ":65535")
fmt.Println("a")
conn, _ := ln.Accept()
fmt.Println("a")
messages := make(chan string)
client := NewClient(conn, messages)
if client.conn != conn {
t.Errorf("NewClient(%q, %q).conn == %q, want %q", 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 (
"bufio"
"net"
"reflect"
"testing"
)
func TestNewClient(t *testing.T) {
conn := &net.IPConn{}
messages := make(chan string)
want := &Client{
counter: 0,
conn: conn,
bufin: bufio.NewReader(conn),
bufout: bufio.NewWriter(conn),
messages: messages,
state: "waiting",
}
got := NewClient(conn, messages)
if !reflect.DeepEqual(got, want) {
t.Errorf("NewClient(%q, %q).conn == %q, want %q", conn, messages, got, want)
}
}
</code></pre>
<p>P.S. I am assuming it is "counter int" and not "counter integer".</p></pre>