title: Using different classloaders for different JUnit tests?
body: <p>I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.</p>
  
  <p>Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader. </p>
  
  <p>Is there any way with JUnit (or with another unit testing package) to do this?</p>
  
  <p>edit: here is some of the Factory code that is in use:</p>
  
  <pre><code>private static MyClass myClassImpl = instantiateMyClass();
  
  private static MyClass instantiateMyClass() {
      MyClass newMyClass = null;
      String className = null;
  
      try {
          Properties props = getProperties();
          className = props.getProperty(PROPERTY_CLASSNAME_KEY);
  
          if (className == null) {
              log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY
                      + "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]");
              className = DEFAULT_CLASSNAME;
          }
  
          Class MyClassClass = Class.forName(className);
          Object MyClassObj = MyClassClass.newInstance();
          if (MyClassObj instanceof MyClass) {
              newMyClass = (MyClass) MyClassObj;
          }
      }
      catch (...) {
          ...
      }
  
      return newMyClass;
  }
  
  private static Properties getProperties() throws IOException {
  
      Properties props = new Properties();
  
      InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
  
      if (stream != null) {
          props.load(stream);
      }
      else {
          log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found");
      }
  
      return props;
  }
  </code></pre>