@BeforeClass: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
   │
   │
   └── SomeTest.java
   └── SomeTest.java
          @BeforeClass
        @BeforeClass
          public static void methodB() {
        public static void methodB() {
            ...
          ...
          }
        }
 
</font>
then both methods are executed only once, in this order: first the parent class method, then the subclass method (<code>methodA()</code> → <code>methodB()</code>). The rule holds true in a multi-layer hierarchy.


However, if both methods '''have the same name''', an override of sorts takes place and only the method belonging to the subclass is executed:
<font size='-1'>
TestBase.java
  │  @BeforeClass
  │  public static void someMethod() {
  │    ...
  │  }
  │
  └── SomeTest.java
        @BeforeClass
        public static void someMethod() {
          ...
        }
</font>
</font>
Only <code>SomeTest.someMethod()</code> is executed, so if you need the logic executed in superclass, it must be invoked explicitly with:
<syntaxhighlight lang='java'>
class SomeTest {
  @BeforeClass
  public static void someMethod() {
    TestBase.someMethod();
  }
}
<syntaxhighlight lang='java'>

Revision as of 01:51, 29 August 2021

Internal

Overview

The annotation must be attached to a static method.

If two methods with different names are annotated with @BeforeClass in a test class hierarchy, as shown below:

TestBase.java
  │  @BeforeClass
  │  public static void methodA() {
  │     ...
  │  }
  │
  └── SomeTest.java
        @BeforeClass
        public static void methodB() {
          ...
        }

then both methods are executed only once, in this order: first the parent class method, then the subclass method (methodA()methodB()). The rule holds true in a multi-layer hierarchy.

However, if both methods have the same name, an override of sorts takes place and only the method belonging to the subclass is executed:

TestBase.java
  │  @BeforeClass
  │  public static void someMethod() {
  │     ...
  │  }
  │
  └── SomeTest.java
        @BeforeClass
        public static void someMethod() {
          ...
        }

Only SomeTest.someMethod() is executed, so if you need the logic executed in superclass, it must be invoked explicitly with: <syntaxhighlight lang='java'> class SomeTest {

 @BeforeClass
 public static void someMethod() {
    TestBase.someMethod();
 }

} <syntaxhighlight lang='java'>