简体   繁体   English

如何在TestSuite界面中使用junit @Beforeclass && @Afterclass?

[英]How can I have a junit @Beforeclass && @Afterclass in my TestSuite interface?

Problem: I have a custom Interface for a TestSuite . 问题:我有一个用于TestSuite的自定义接口。

public interface TestSuite {

  abstract void setupRestAssuredForSuite();
  abstract void restoreDatabase();
  abstract void executeSuitePreparation();
  abstract void executeSuiteTearDown();

}

How can I have my interface contain @BeforeClass and @AfterClass annotations from junit and my implementations of the TestSuite interface to acknowledge those? 如何让我的界面包含来自junit的@BeforeClass和@AfterClass批注以及我对TestSuite接口的实现,以确认它们? Should I be doing this another way completely? 我应该完全用另一种方式吗? I am curious to know if such a thing is possible with interfaces. 我很想知道接口是否可以实现这种功能。

do I need to write the annotations manually in every class which implements TestSuite? 我需要在实现TestSuite的每个类中手动编写注释吗? or can I have the executeSuitePreparation(); 或者我可以拥有executeSuitePreparation(); and executeSuiteTearDown(); executeSuiteTearDown(); methods running without the annotations because they somehow exist in TestSuite itself and I just need to implement the code behind setup/teardown. 没有注释运行的方法,因为它们以某种方式存在于TestSuite本身中,我只需要实现设置/拆卸的代码即可。

public class Foo extends Bar implements TestSuite

To my knowledge the @Beforeclass and @Afterclass methods must be static. 据我所知,@Beforeclass和@Afterclass方法必须是静态的。

Is this a silly way of approaching the situation? 这是解决情况的愚蠢方法吗? Could you recommend a different way of doing it if that is the case. 如果是这种情况,您能推荐一种不同的方法吗?

You're trying to use interfaces as mixins. 您正在尝试使用接口作为mixin。 Interfaces are not mixins. 接口不是mixin。

Probably the best you can do is to write static methods in your interface that do the required setup: 可能最好的办法是在您的界面中编写静态方法以完成所需的设置:

public interface TestSuite {

  abstract void setupRestAssuredForSuite();
  ...


  static SomeReturn setup()
  {
      Database database = new Database();
      ...
      return database;
  }

  static void teardown(SomeType foo)
  {
      foo.reset();
  }
}

Then in your concrete implementations you can do: 然后,在您的具体实现中,您可以执行以下操作:

public class Foo extends Bar implements TestSuite
{
    private static Foo foo;

    @BeforeClass
    public void beforeClass()
    {
        foo = TestSuite.setup();
    }

    @BeforeClass
    public void beforeClass()
    {
        TestSuite.teardown(foo);
    }
}

I would strongly encourage you to re-think whether you need to use inheritance in your tests. 强烈建议您重新考虑是否需要在测试中使用继承。 It seems like a code smell to me, and indicates that your tests are perhaps not focused enough. 在我看来,这似乎是一种代码气味,并表明您的测试可能不够集中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM