junit-team / junit4

A programmer-oriented testing framework for Java.
https://junit.org/junit4
Eclipse Public License 1.0
8.51k stars 3.24k forks source link

Thread context classloader not reset between tests #1743

Closed gregw closed 2 years ago

gregw commented 2 years ago

The thread context classloader is not reset between tests. This means that a test that passes, yet leaves the thread context classloader set may break a subsequent test, which itself passes if run by itself. For example:

public class ContextClassLoaderTest
{
    static final ClassLoader LingeringLoader = new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader());

    @Test
    public void testA()
    {
        assertThat(Thread.currentThread().getContextClassLoader(), not(sameInstance(LingeringLoader)));
        Thread.currentThread().setContextClassLoader(LingeringLoader);
    }

    @Test void testB()
    {
        assertThat(Thread.currentThread().getContextClassLoader(), not(sameInstance(LingeringLoader)));
        Thread.currentThread().setContextClassLoader(LingeringLoader);
    }
}

Both testA and testB pass if run by themselves, but if run together, then the second always fails.

I tried a similar test with the thread interrupted status and noted that we reset between test runs, so I think the thread context loader should also be reset.

gregw commented 2 years ago

Closed in favour of https://github.com/junit-team/junit5/issues/2942