junit5 icon indicating copy to clipboard operation
junit5 copied to clipboard

Inherited @BeforeEach method executed on wrong instance for @Nested class

Open mikosik opened this issue 6 years ago • 3 comments

Steps to reproduce

code

package org.myproject;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class OuterClass extends SuperClass {
  @Nested
  public class NestedClass extends SuperClass {
    @Test
    public void test() {
      // empty test
    }
  }
}

class SuperClass {
  @BeforeEach
  public void beforeEach() {
    System.out.println("beforeEach() for " + this.toString());
  }
}

Actual behaviour

Running the only test method from the code above results in invocation of beforeEach() method on the same instance of NestedClass twice before running test() method. On instance of OuterClass method beforeEach() is never invoked. This can be verified by looking at console output:

beforeEach() for org.myproject.OuterClass$NestedClass@5bda8e08
beforeEach() for org.myproject.OuterClass$NestedClass@5bda8e08

The problem is most probably caused by the fact that both OuterClass and NestedClass extends the same SuperClass. I guess similar problem may exists for @BeforeAll @AfterEach, @AfterAll but I didn't check that assumption.

Expected behaviour

Running test should result in beforeEach() method being invoked once on instance of OuterClass and once on instance of NestedClass.

Context

I reproduced that on IntelliJ IDEA 2020.1.1 (Community Edition) Build #IC-201.7223.91, built on April 30, 2020 with junit fetched from maven via:

org.junit.vintage:junit-vintage-engine:5.6.2
org.junit.jupiter:junit-jupiter-engine:5.6.2
org.junit.jupiter:junit-jupiter-params:5.6.2
org.junit.platform:junit-platform-launcher:1.6.2

mikosik avatar May 14 '20 09:05 mikosik

Thanks for reporting the issue and providing the example to reproduce this.

I have confirmed that this is a bug and that the cause is likely the use of Method.getDeclaringClass() in ClassBasedTestDescriptor.invokeMethodInExtensionContext(...).

In other words, we'll likely need to revise how we invoke TestInstances.findInstance(Class<?>) in order to find the correct target for such use cases.

sbrannen avatar May 14 '20 11:05 sbrannen

Tentatively slated for 5.7 M2 for team discussion

sbrannen avatar May 14 '20 11:05 sbrannen

This seems indeed to be the case. Checked the proposed test case as well as a variant with two separate super-classes. The behaviour of the latter is correct.

mmerdes avatar Jul 01 '20 20:07 mmerdes