title: How to test Golang channels / go-routines
body: <p>I have a type that contains a byte of data, and takes a channel to post new data there. Other code can read the last written byte of data using a <code>Read</code> function. </p>
  
  <p>Edit: for actual, runnable code, see <a href="https://github.com/ariejan/i6502/pull/3" rel="nofollow">https://github.com/ariejan/i6502/pull/3</a> especially files acia6551.go and acia6551_test.go. Tests results can be viewed here: <a href="https://travis-ci.org/ariejan/i6502/jobs/32862705" rel="nofollow">https://travis-ci.org/ariejan/i6502/jobs/32862705</a></p>
  
  <p>I have the following:</p>
  
  <pre><code>// Emulates a serial interface chip of some kind.
  type Unit struct {
    // Channel used for others to use, bytes written here will be placed in rxChar
    Rx chan byte
  
    // Internal store of the last byte written.
    rxChar byte // Internal storage
  }
  
  // Used internally to read data store in rxChar
  func (u *Unit) Read() byte {
    return u.rxChar
  }
  
  // Create new Unit and go-routing to listen for Rx bytes
  func NewUnit(rx chan byte) *Unit {
    unit := &amp;Unit{Rx: rx}
  
    go func() {
      for {
        select {
        case data := &lt;-unit.Rx:
          unit.rxData = data
          fmt.Printf("Posted 0x%02X\n", data)
        }
      }
    }()
  
    return unit
  }
  </code></pre>
  
  <p>My test looks like this:</p>
  
  <pre><code>func TestUnitRx(t *testing.T) {
    rx := make(chan byte)
    u := NewUnit(rx)
  
    // Post a byte to the Rx channel
    // This prints "Posted 0x42", as you'd expect
    rx &lt;- 0x42
  
    // Using testing
    // Should read last byte, 0x42 but fails.
    fmt.Println("Reading value...")
    assert.Equal(t, 0x42, u.Read()) 
  }
  </code></pre>
  
  <p>At first I figured the "Reading value" happened before the go-routing got around to writing the data. But the "Posted" message is always printed before "Reading".</p>
  
  <p>So, two questions remain:</p>
  
  <ul>
  <li>Is this the best way to handle an incoming stream of bytes (at 9600 baud ;-))</li>
  <li>If this is the right way, how can I properly test it or what is wrong with my code?</li>
  </ul>