Skip to content

Instantly share code, notes, and snippets.

@BenWhitehead
Last active June 24, 2017 00:54
Show Gist options
  • Save BenWhitehead/b40069372a69741a2612bab8ecbd9f9c to your computer and use it in GitHub Desktop.
Save BenWhitehead/b40069372a69741a2612bab8ecbd9f9c to your computer and use it in GitHub Desktop.
Static method shadowing
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Parent {
private static final Logger LOGGER = LoggerFactory.getLogger(Parent.class);
@BeforeClass
public static void beforeClass() {
LOGGER.debug("beforeClass()");
}
@AfterClass
public static void afterClass() {
LOGGER.debug("afterClass()");
}
}
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
public class Child1 extends Parent {
private static final Logger LOGGER = LoggerFactory.getLogger(Child1.class);
@BeforeClass
public static void beforeClass() {
LOGGER.debug("beforeClass()");
}
@Test
public void name() throws Exception {
LOGGER.debug("name()");
assertTrue(true);
}
}
17:39:34.100 DEBUG [main] Child1 - beforeClass()
17:39:34.106 DEBUG [main] Child1 - name()
17:39:34.107 DEBUG [main] Parent - afterClass()
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
public class Child2 extends Parent {
private static final Logger LOGGER = LoggerFactory.getLogger(Child2.class);
@BeforeClass
public static void beforeClass2() {
LOGGER.debug("beforeClass2()");
}
@Test
public void name() throws Exception {
LOGGER.debug("name()");
assertTrue(true);
}
}
17:40:10.451 DEBUG [main] Parent - beforeClass()
17:40:10.453 DEBUG [main] Child2 - beforeClass2()
17:40:10.454 DEBUG [main] Child2 - name()
17:40:10.455 DEBUG [main] Parent - afterClass()
@BenWhitehead
Copy link
Author

However, if we make Parent#beforeClass final like it should be, Child1 results in a compile error and the shadowing is avoided.

Since JUnit4 is annotation driven and not subclass driven, many methods can be annotated with @BeforeClass and will be executed in what appears to be parent to child order, however the order is undefined within the same class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment