超类和带有JUnit5测试的抽象测试方法

huangapple go评论95阅读模式
英文:

Super class and abstract test method with JUnit5 tests

问题

我将单元测试从JUnit4迁移到JUnit5,并且我使用IntelliJ作为IDE。在JUnit4中,我有一些测试实现了测试超类的两种方法。似乎我可以在抽象方法上放置@Test,然后只需在子类中重写它们。

  1. import org.junit.jupiter.api.Test;
  2. @SpringBootTest(classes = {TestContext.class})
  3. public abstract class AbstractTest {
  4. @Test
  5. public abstract void testOk();
  6. @Test
  7. public abstract void testKo();
  8. }

以及测试

  1. public class SomeTest extends AbstractTest {
  2. // 使用JUnit5的@Test注解
  3. @Override
  4. public void testOk() {
  5. //
  6. }
  7. // 使用JUnit5的@Test注解
  8. @Override
  9. public void testKo() {
  10. //
  11. }
  12. }

但是在JUnit5中,似乎我必须在子类SomeTest的重写方法上放置@Test注解,否则无法找到测试。是否有一种方法可以在JUnit5中实现以前的配置,避免为所有子类方法添加@Test

英文:

I migrated unit tests from JUnit4 to JUnit5 and I use Intellij as IDE
With JUnit4, I had some tests implementing two methodes of a test superclass. It seems like I could put the @Test on the abstract methods and just override them in subclasses.

  1. import org.junit.jupiter.api.Test;
  2. @SpringBootTest(classes = {TestContext.class})
  3. public abstract class AbstractTest {
  4. @Test
  5. public abstract void testOk();
  6. @Test
  7. public abstract void testKo();
  8. }

And the test

  1. public class SomeTest extends AbstractTest {
  2. // @Test with JUnit5
  3. @Override
  4. public void testOk() {
  5. //
  6. }
  7. // @Test with JUnit5
  8. @Override
  9. public void testKo() {
  10. //
  11. }
  12. }

But with JUnit5, it seems like I have to put @Test annotation on the overriding method of the subclass SomeTest, otherwise tests are not found. Is there a way to achieve my previous configuration with JUnit5, avoiding to add @Test to all subclasses methods ?

答案1

得分: 0

根据M. Deinum的建议,我最终得到了这个:

  1. import org.junit.jupiter.api.Test;
  2. @SpringBootTest(classes = {TestContext.class})
  3. public abstract class AbstractTest {
  4. public abstract void testOk();
  5. public abstract void testKo();
  6. @Test
  7. public void junitTestOk() {
  8. this.testOk();
  9. }
  10. @Test
  11. public void junitTestKo() {
  12. this.testKo();
  13. }
  14. }
英文:

Following M. Deinum recommandation, I ended up with this

  1. import org.junit.jupiter.api.Test;
  2. @SpringBootTest(classes = {TestContext.class})
  3. public abstract class AbstractTest {
  4. public abstract void testOk();
  5. public abstract void testKo();
  6. @Test
  7. public void junitTestOk() {
  8. this.testOk();
  9. }
  10. @Test
  11. public void junitTestKo() {
  12. this.testKo();
  13. }
  14. }

huangapple
  • 本文由 发表于 2023年6月15日 17:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定