<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>

[{'answer_id': 42108, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 2, 'selected': False, 'text': "<p>When I run into these sort of situations I prefer to use what is a bit of a hack.  I might instead expose a protected method such as reinitialize(), then invoke this from the test to effectively set the factory back to its initial state.  This method only exists for the test cases, and I document it as such.</p>\n\n<p>It is a bit of a hack, but it's a lot easier than other options and you won't need a 3rd party lib to do it (though if you prefer a cleaner solution, there probably are some kind of 3rd party tools out there you could use).</p>\n"}, {'answer_id': 42130, 'author': 'Cem Catikkas', 'author_id': 3087, 'author_profile': 'https://Stackoverflow.com/users/3087', 'pm_score': 2, 'selected': False, 'text': '<p>You can use Reflection to set <code>myClassImpl</code> by calling <code>instantiateMyClass()</code> again. Take a look at <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#34658">this answer</a> to see example patterns for playing around with private methods and variables.</p>\n'}, {'answer_id': 9192126, 'author': 'AutomatedMike', 'author_id': 352035, 'author_profile': 'https://Stackoverflow.com/users/352035', 'pm_score': 5, 'selected': False, 'text': '<p>This question might be old but since this was the nearest answer I found when I had this problem I though I\'d describe my solution.</p>\n\n<p><strong>Using JUnit 4</strong></p>\n\n<p>Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class)</p>\n\n<p>Add the <code>@RunWith(SeparateClassloaderTestRunner.class)</code> annotation to your test classes.</p>\n\n<p>Create the <code>SeparateClassloaderTestRunner</code> to look like this:</p>\n\n<pre><code>public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {\n\n    public SeparateClassloaderTestRunner(Class&lt;?&gt; clazz) throws InitializationError {\n        super(getFromTestClassloader(clazz));\n    }\n\n    private static Class&lt;?&gt; getFromTestClassloader(Class&lt;?&gt; clazz) throws InitializationError {\n        try {\n            ClassLoader testClassLoader = new TestClassLoader();\n            return Class.forName(clazz.getName(), true, testClassLoader);\n        } catch (ClassNotFoundException e) {\n            throw new InitializationError(e);\n        }\n    }\n\n    public static class TestClassLoader extends URLClassLoader {\n        public TestClassLoader() {\n            super(((URLClassLoader)getSystemClassLoader()).getURLs());\n        }\n\n        @Override\n        public Class&lt;?&gt; loadClass(String name) throws ClassNotFoundException {\n            if (name.startsWith("org.mypackages.")) {\n                return super.findClass(name);\n            }\n            return super.loadClass(name);\n        }\n    }\n}\n</code></pre>\n\n<p>Note I had to do this to test code running in a legacy framework which I couldn\'t change. Given the choice I\'d reduce the use of statics and/or put test hooks in to allow the system to be reset.  It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise.</p>\n\n<p>Also this solution breaks anything else that relies on classloading tricks such as Mockito.</p>\n'}, {'answer_id': 17805809, 'author': 'barclar', 'author_id': 329736, 'author_profile': 'https://Stackoverflow.com/users/329736', 'pm_score': 2, 'selected': False, 'text': '<p>If executing Junit via the <a href="http://ant.apache.org/manual/Tasks/junit.html" rel="nofollow">Ant task</a> you can set <strong><code>fork=true</code></strong> to execute every class of tests in it\'s own JVM. Also put each test method in its own class and they will each load and initialise their own version of <code>MyClass</code>. It\'s extreme but very effective.</p>\n'}, {'answer_id': 34154189, 'author': 'Neeme Praks', 'author_id': 74694, 'author_profile': 'https://Stackoverflow.com/users/74694', 'pm_score': 1, 'selected': False, 'text': '<p>Below you can find a sample that does not need a separate JUnit test runner and works also with classloading tricks such as Mockito.</p>\n\n<pre><code>package com.mycompany.app;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\nimport java.net.URLClassLoader;\n\nimport org.junit.Test;\n\npublic class ApplicationInSeparateClassLoaderTest {\n\n  @Test\n  public void testApplicationInSeparateClassLoader1() throws Exception {\n    testApplicationInSeparateClassLoader();\n  }\n\n  @Test\n  public void testApplicationInSeparateClassLoader2() throws Exception {\n    testApplicationInSeparateClassLoader();\n  }\n\n  private void testApplicationInSeparateClassLoader() throws Exception {\n    //run application code in separate class loader in order to isolate static state between test runs\n    Runnable runnable = mock(Runnable.class);\n    //set up your mock object expectations here, if needed\n    InterfaceToApplicationDependentCode tester = makeCodeToRunInSeparateClassLoader(\n        "com.mycompany.app", InterfaceToApplicationDependentCode.class, CodeToRunInApplicationClassLoader.class);\n    //if you want to try the code without class loader isolation, comment out above line and comment in the line below\n    //CodeToRunInApplicationClassLoader tester = new CodeToRunInApplicationClassLoaderImpl();\n    tester.testTheCode(runnable);\n    verify(runnable).run();\n    assertEquals("should be one invocation!", 1, tester.getNumOfInvocations());\n  }\n\n  /**\n   * Create a new class loader for loading application-dependent code and return an instance of that.\n   */\n  @SuppressWarnings("unchecked")\n  private &lt;I, T&gt; I makeCodeToRunInSeparateClassLoader(\n      String packageName, Class&lt;I&gt; testCodeInterfaceClass, Class&lt;T&gt; testCodeImplClass) throws Exception {\n    TestApplicationClassLoader cl = new TestApplicationClassLoader(\n        packageName, getClass(), testCodeInterfaceClass);\n    Class&lt;?&gt; testerClass = cl.loadClass(testCodeImplClass.getName());\n    return (I) testerClass.newInstance();\n  }\n\n  /**\n   * Bridge interface, implemented by code that should be run in application class loader.\n   * This interface is loaded by the same class loader as the unit test class, so\n   * we can call the application-dependent code without need for reflection.\n   */\n  public static interface InterfaceToApplicationDependentCode {\n    void testTheCode(Runnable run);\n    int getNumOfInvocations();\n  }\n\n  /**\n   * Test-specific code to call application-dependent code. This class is loaded by \n   * the same class loader as the application code.\n   */\n  public static class CodeToRunInApplicationClassLoader implements InterfaceToApplicationDependentCode {\n    private static int numOfInvocations = 0;\n\n    @Override\n    public void testTheCode(Runnable runnable) {\n      numOfInvocations++;\n      runnable.run();\n    }\n\n    @Override\n    public int getNumOfInvocations() {\n      return numOfInvocations;\n    }\n  }\n\n  /**\n   * Loads application classes in separate class loader from test classes.\n   */\n  private static class TestApplicationClassLoader extends URLClassLoader {\n\n    private final String appPackage;\n    private final String mainTestClassName;\n    private final String[] testSupportClassNames;\n\n    public TestApplicationClassLoader(String appPackage, Class&lt;?&gt; mainTestClass, Class&lt;?&gt;... testSupportClasses) {\n      super(((URLClassLoader) getSystemClassLoader()).getURLs());\n      this.appPackage = appPackage;\n      this.mainTestClassName = mainTestClass.getName();\n      this.testSupportClassNames = convertClassesToStrings(testSupportClasses);\n    }\n\n    private String[] convertClassesToStrings(Class&lt;?&gt;[] classes) {\n      String[] results = new String[classes.length];\n      for (int i = 0; i &lt; classes.length; i++) {\n        results[i] = classes[i].getName();\n      }\n      return results;\n    }\n\n    @Override\n    public Class&lt;?&gt; loadClass(String className) throws ClassNotFoundException {\n      if (isApplicationClass(className)) {\n        //look for class only in local class loader\n        return super.findClass(className);\n      }\n      //look for class in parent class loader first and only then in local class loader\n      return super.loadClass(className);\n    }\n\n    private boolean isApplicationClass(String className) {\n      if (mainTestClassName.equals(className)) {\n        return false;\n      }\n      for (int i = 0; i &lt; testSupportClassNames.length; i++) {\n        if (testSupportClassNames[i].equals(className)) {\n          return false;\n        }\n      }\n      return className.startsWith(appPackage);\n    }\n\n  }\n\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/42102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4249/']