如何在子类中重写、禁用或修改父类的嵌套测试类及方法?
解决方案:禁用或修改父类抽象测试类的嵌套测试方法
针对你提出的在SomeTest中处理父类SuperclassTest里ToStringTest#_NotBlank_NewInstance测试的需求,以下是两种常见实现方式:
一、禁用指定测试方法
在子类中重新定义同名的嵌套测试类ToStringTest,然后覆盖目标测试方法并添加@Disabled注解,JUnit 5会优先执行子类的测试方法,从而禁用父类的对应测试:
class SomeTest extends SuperclassTest<Some> { SomeTest() { super(Some.class); } // 重写嵌套测试类,禁用目标方法 @Nested class ToStringTest { @Override @Disabled("当前Some类的toString()允许为空,禁用该校验") void _NotBlank_NewInstance() { super._NotBlank_NewInstance(); } } }
二、修改测试方法逻辑
如果需要替换原测试的校验逻辑,同样在子类的嵌套测试类中覆盖方法,编写自定义的测试逻辑即可:
class SomeTest extends SuperclassTest<Some> { SomeTest() { super(Some.class); } // 重写嵌套测试类,修改测试逻辑 @Nested class ToStringTest { @Override void _NotBlank_NewInstance() { // 自定义测试逻辑,比如允许toString为空,或者修改校验规则 String string = newInstance().toString(); assertThat(string).contains("Some"); // 替换为自己需要的断言 } } }
注意事项
- 确保父类的
newInstance()方法是protected访问权限,这样子类的嵌套类可以调用它。如果父类中没有该方法,需要补充实现:protected T newInstance() { try { return typeClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to create instance", e); } } - JUnit 5中,子类的嵌套类会覆盖父类的同名嵌套类,因此子类中定义的
ToStringTest会替代父类的对应嵌套类。
内容的提问来源于stack exchange,提问作者Jin Kwon
相关产品推荐
相关产品推荐

