javainheritanceinner-classesjunit-jupiter

How can I override super.nested test class?


Say, I have an abstract superclass and an abstract test class for testing subclasses.

abstract class Superclass {
}

@RequiredArgsConstructor
abstract class SuperclassTest<T extends Superclass> {

    SuperclassTest(Class<T> typeClass) {
        super();
        this.typeClass = typeClass;
    }

    @Nested
    class ToStringTest {

         @Test
         void _NotBlank_NewInstance() {
             String string = newInstance().toString();
             assertThat(string).isNotBlank();
         }
    }

    final Class<T> typeClass;
}

Now, how can I override the nested test class/method for disabling or modifying?

class SomeTest extends SuperclassTest<Some> {

    SomeTest() {
        super(Some.class)
    }

    // How can I disable or change ToStringTest#_NotBlank_NewInstance?
}

Solution

  • If you need to extend the inner class ToStringTest within SomeTest, and override the method _NotBlank_NewInstance(), you can create a subclass SomeToStringTest in SomeTest and make it extend SuperclassTest.ToStringTest. At this point, you can override _NotBlank_NewInstance() with the desired behavior.

    class SomeTest extends SuperclassTest<Some> {
    
        SomeTest() {
            super(Some.class);
        }
    
        // Extending the inner class
        class SomeToStringTest extends SuperclassTest.ToStringTest {
    
            @Test
            @Override
            void _NotBlank_NewInstance() {
                //modify the implementation
            }
        }
    }