title: How to "insulate" Singletons in JUnit?
body: <p>I'm using a 3rd party library for a server / client program. The server / client allow to register a specific data model (details are not important at all here).</p>
  
  <p>In my unit tests, I have roughly the following:</p>
  
  <pre><code>private static MyServerType myServer;  // my class, derived from a 3rd party class
  private static MyClientType myClient;  // my class, derived from 3rd party
  private static int modelId = 123;      // identifier to identify the data model
  
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
      int modelId
      myServer = new MyServerType();
      myServer.registerDataModel(modelId, new ServerDataModel());
      myClient = new MyClientType();
      myClient.registerDataModel(modelId, new ClientDataModel());
  
  }
  </code></pre>
  
  <p>When I run this code, it fails - because internally (we can look at the source code), the library has a <strong>Singleton</strong> (static class with .getInstance() ) which registers the models by Id, and finds that there is already a model with this Id registered.</p>
  
  <p>How can I run the unit tests where I want to test the client / server interaction? (Both the server and client are own programs derived from the 3rd party library classes, so I need to test both, and their interaction)</p>
  
  <p>In the <code>@BeforeClass</code> method I could start an external (java) program which runs the freshly compiled server. This looks somehow quite ugly.</p>
  
  <p>Is there a way to "insulate" the server or client within the unit test (like a "virtual machine" inside the JVM :) for either process), so that getInstance() returns different objects for server and client, grouped e.g. by thread / thread group or something similar?</p>
  
  <p>ps: yes, this is an example why singletons are evil - but I have to live with it.</p>
  
  <p><strong>EDIT:</strong> I have split the business logic from the server logic so that I can test business logic independently. What I want to test is that the server works as proper front-end for the business logic, that is, updates all data changes and triggers function calls on the business logic on user requests.</p>
  
  <p>Is this kind of test "too big" for a unit test (i.e. integration test)? </p>
  
  <p>Especially: If I use only a trivial client, i.e. a stub client which just speaks the protocol, just to test that the server provides the correct data etc. - would such tests (e.g. <code>@Test public void test_publishes_updates_on_VARIABLEX() { ... }</code> <code>@Test public void test_calls_backend_functionY_and_returns_formatted_reply() { ... }</code> ) be unit tests?</p>