JUnit with singletons What do people think about adding the functionality into JUnit to enable one to load and unload singletons during tests. This can be very helpful, if, for example, several possible states of the singleton that cannot be achieved in succession need to be tested. I've come up against it recently.

Janne Nykänen

Well, one way to allow one JUnit testcase to test a singleton class with more that one initialization params is to use a custom classloader to load your singleton; every test-method needs to instantiate a new TestClassLoader instance (a class that extends the jdk ClassLoader). I did it like this:

public class TestClassLoader extends ClassLoader
{
    public Class findClass(String name) throws ClassNotFoundException
    {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name)
        throws ClassNotFoundException
    {
        InputStream stream =
            getClass().getClassLoader()
               .getResourceAsStream(name + ".class");

        String path = null;
        try
        {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            int i;
            while ((i = stream.read()) != -1)
            {
                bOut.write(i);
            }
            return bOut.toByteArray();
        }
        catch (FileNotFoundException ex)
        {
            throw new ClassNotFoundException(
                "Class " + name + " could not be found from " + path,
                ex);
        }
        catch (IOException ex)
        {
            throw new ClassNotFoundException(
                "Class " + name + " could not be found", ex);
        }
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact