title: Testing Java Sockets
body: <p>I'm developing a network application and I want to get unit testing right.  THIS time we'll do it, you know? :)</p>
  
  <p>I'm have trouble testing network connections, though.  </p>
  
  <p>In my application I use plain <code>java.net.Socket</code>s.  </p>
  
  <p>For example:</p>
  
  <pre><code>import java.io.IOException;
  import java.io.OutputStream;
  import java.net.Socket;
  import java.net.UnknownHostException;
  
  public class Message {
      byte[] payload;
  
      public Message(byte[] payload) {
          this.payload = payload;
      }
  
      public boolean sendTo(String hostname, int port) {
          boolean sent = false;
  
          try {
              Socket socket = new Socket(hostname, port);
  
              OutputStream out = socket.getOutputStream();
  
              out.write(payload);
  
              socket.close();
  
              sent = true;
          } catch (UnknownHostException e) {
          } catch (IOException e) {
          }
  
          return sent;
      }
  }
  </code></pre>
  
  <p>I read about mocking but am not sure how to apply it.</p>