Mocking a tcp server

I have an class that should connect to a server and just wait for
responses. Here's the class, it's very basic

    class Connection
      def initialize(host, port)
        @host, @port = host, port
        @server = TCPSocket.new @host, @port
        listen
      end

      private

      def listen
        Thread.new do
          while cmd = @server.gets
            puts cmd
          end
        end
      end
    end

This seems to work if I connect to a live server. It's not working
perfectly, because it only gets a couple of responses and then quits
before it has all of them. However, if do t = Thread.new.... and then
call t.join after the thread block, it just hangs there. So I'm not
sure what to do about that.

Secondly, I don't know how to mock up the server. I have this class:

class TCPSocket
  def gets
    while $server_messages.empty?
      # just sit and do nothing
    end

      $server_messages.shift
    end
end

and in my unit tests I add a string to $server_messages. If I join my
thread in Connection#listen it just hangs, and if I don't join, it
just exits without getting any messages. How can I listen for
arbitrary messages in another thread, and how can I mock up the
server?

Pat

My recent blog post might give you some ideas:

http://blog.grayproductions.net/articles/2006/04/21/phoned-in-testing-post

James Edward Gray II

···

On Apr 23, 2006, at 3:04 AM, Pat Maddox wrote:

Secondly, I don't know how to mock up the server.