mardi 1 décembre 2015

Testing constructors in Go

How I can test my NewClient constructor for my Client struct ?

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",

    }
}

I tried some testing like this:

package busybus

import (
    "net"
    "testing"
)

func TestNewClient(t *testing.T) {
    ln, _ := net.Listen("tcp", ":65535")
    conn, _ := ln.Accept()
    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)
    }
}

But this hangs during the test runs due to ln.Accept, it seems a totally wrong approach anyway... any suggestion how I can test this constructor ?

Aucun commentaire:

Enregistrer un commentaire