Skip to content

Commit

Permalink
Avoid initialising classes when looking for tests (#207)
Browse files Browse the repository at this point in the history
This can cause hidden problems where there are ordering issues between
(eg) setup methods and static fields in classes.
  • Loading branch information
shs96c authored Sep 7, 2023
1 parent e3e26fb commit 7cfa522
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public boolean run(String testClassName) {

final Class<?> testClass;
try {
testClass = Class.forName(testClassName);
testClass = Class.forName(testClassName, false, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to find testClass", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.github.bazel_contrib.contrib_rules_jvm.junit5;

import static org.junit.jupiter.api.Assertions.assertNotEquals;

import org.junit.jupiter.api.Test;

public class StaticInitializerTest extends StaticInitializerTestBase {

// The `value` will only be set if the parent class's `BeforeAll` method
// has been called. If we've called `Class.forName(String)` in the
// `ActualRunner` then this value will be `null`, so the test won't even
// start. This test verifies that while we can still find tests, we're
// not initialising classes until they're used.
private static final int length = value.length();

@Test
public void doSomethingToForceInitializersToBeRun() {
assertNotEquals(0, length);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.github.bazel_contrib.contrib_rules_jvm.junit5;

import org.junit.jupiter.api.BeforeAll;

public class StaticInitializerTestBase {

protected static String value;

@BeforeAll
public static void setTestData() {
value = "Hello, World!";
}
}

0 comments on commit 7cfa522

Please sign in to comment.