【问题标题】:How to use @BeforeClass and @AfterClass within a JerseyTest suite如何在 JerseyTest 套件中使用 @BeforeClass 和 @AfterClass
【发布时间】:2016-12-03 22:37:23
【问题描述】:

事实证明,JUnit 想要 @BeforeClass@AfterClass 是静态的,这与 JerseyTest 的 configure 方法覆盖不符。是否有一种已知的方式来配置 Jersey 应用程序,同时仍然能够访问 JUnit 的实用程序方法?

public class MyControllerTest  extends JerseyTest {
  @BeforeClass
  public static void setup() throws Exception {
    target("myRoute").request().post(Entity.json("{}"));
  }
  @Override
  protected Application configure() {
      return new AppConfiguration();
  }
}

因此beforeClass 需要是静态的,target 因为它的实例方法性质而不能被调用。在尝试改用构造函数时,发现configureconstructor 之后运行,这会阻止执行设置请求,因此自然会失败。

任何建议都非常感谢,谢谢!

【问题讨论】:

  • 那么,为什么您首先希望setup() 方法是静态的?你不能让它成为会员并使用@Before吗?
  • 你试过@Before而不是@BeforeClass吗?
  • 这是一个繁重且可能耗时的操作,我不想在每个测试中都运行它。 @Dimitri
  • JUnit whats @BeforeClass 方法是静态的,不幸的是,这不是选择问题@hfhc2
  • 另一种解决方案是定义一个Junit Rule并使用注解@ClassRule。

标签: java junit junit4 jersey-2.0 jersey-test-framework


【解决方案1】:

为了避免在这种情况下进行繁重的设置,我们在几种情况下所做的是使用布尔标志来有条件地运行该设置。

public class MyControllerTest extends JerseyTest {

  private static myRouteSetupDone = false;

  @Before
  public void setup() throws Exception {
    if (!myRouteSetupDone) {
      target("myRoute").request().post(Entity.json("{}"));
      myRouteSetupDone = true;
    }
  }
  @Override
  protected Application configure() {
      return new AppConfiguration();
  }
}

【讨论】:

    【解决方案2】:

    @Before 不需要 static 修饰符,并且会在每个测试方法之前执行。

    【讨论】:

    • 这是一个繁重且可能耗时的操作,我不想在每个测试中都运行它。
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 2016-08-15
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多