title: Starting and stopping a Jetty server between JUnit tests
body: <p>I'm trying to simulate tests of various run-throughs of my program, setting up a Jetty server in a <code>@Before</code> method and closing it down in an <code>@After</code>. </p>
  
  <p>My first test will run successfully, but upon attempting to POST data in following tests <code>com.sun.jersey.api.client.ClientHandlerException: java.net.SocketException: Software caused connection abort: recv failed</code> occurs. Is there any way I can get my Server (and Client?) to shut down cleanly between tests?</p>
  
  <p>My Before and After code is as follows:</p>
  
  <pre><code>@Before
  public void startServer() {
      try {
          server = new Server(8080);
          ServletContextHandler root = new ServletContextHandler(server, "/ingest", ServletContextHandler.SESSIONS);
  
          root.addServlet(new Servlet(), "/*");
  
          server.start();
  
          client = new Client();
          client.setChunkedEncodingSize(16 * 1024);
  
          FileInputStream stream = new FileInputStream(testFile);
          try {
              client.resource(uri).type(MediaType.APPLICATION_OCTET_STREAM).post(stream);
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              Closeables.closeQuietly(stream);
              client.destroy();
          }
      } catch (Exception e) {
          e.printStackTrace();
          fail("Unexpected Exception when starting up server.");
      }
  }
  
  @After
  public void shutDown() {
      if (output.exists()) {
          output.delete();
      }
      try {
          server.stop();
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
  </code></pre>