Skip to content

Commit

Permalink
Make sure to revert to previous ClassLoader in tests
Browse files Browse the repository at this point in the history
Otherwise we see strange issues if the ClassLoader
is closed as part of tests.
  • Loading branch information
centic9 committed Dec 15, 2024
1 parent 32d2434 commit 5bd9a9b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,33 @@ public void testMake() {

@Test
public void testInitLogging() throws IOException {
Thread.currentThread().setContextClassLoader(new ClassLoader() {
@Override
public URL getResource(String name) {
return null;
}
});

try {
LoggerFactory.initLogging();
fail("Should throw Exception, seems we found a resource: " + Thread.currentThread().getContextClassLoader().getResource("logging.properties"));
} catch (IOException e) {
// expected if we do not have a logging.properties here
assertNotNull(e);
}

try (URLClassLoader cl = new URLClassLoader(new URL[] {new File("src/test/resources").toURI().toURL()},
Thread.currentThread().getContextClassLoader())) {
Thread.currentThread().setContextClassLoader(cl);

// now it should work
LoggerFactory.initLogging();
}
ClassLoader prev = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(new ClassLoader() {
@Override
public URL getResource(String name) {
return null;
}
});

try {
LoggerFactory.initLogging();
fail("Should throw Exception, seems we found a resource: " + Thread.currentThread().getContextClassLoader().getResource("logging.properties"));
} catch (IOException e) {
// expected if we do not have a logging.properties here
assertNotNull(e);
}

try (URLClassLoader cl = new URLClassLoader(new URL[] {new File("src/test/resources").toURI().toURL()}, prev)) {
Thread.currentThread().setContextClassLoader(cl);

// now it should work
LoggerFactory.initLogging();
}
} finally {
// restore the previous class loader
Thread.currentThread().setContextClassLoader(prev);
}
}

// helper method to get coverage of the unused constructor
Expand Down
14 changes: 5 additions & 9 deletions src/test/java/org/dstadler/commons/svn/SVNCommandsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,11 @@ public class SVNCommandsTest {

// use static-block to initialize "static final" members
static {
assertNotNull(Thread.currentThread().getContextClassLoader().getResource("logging.properties"),
"Should have logging.properties, but had none with Classloader: " +
Thread.currentThread().getContextClassLoader());

try {
LoggerFactory.initLogging();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
LoggerFactory.initLogging();
} catch (IOException e) {
throw new RuntimeException(e);
}

repoDir = createLocalSVNRepository();

Expand Down

0 comments on commit 5bd9a9b

Please sign in to comment.