Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

java - AfterAll global hook cucumber-jvm

I'm using cucumber-jvm in my integration tests and I need to execute some code after all scenarios are finished, just once.

After reading carefully some posts like this and reviewed this reported issue, I've accomplished it doing something like this:

public class ContextSteps {

   private static boolean initialized = false;

   @cucumber.api.java.Before
   public void setUp() throws Exception {
      if (!initialized) {
         // Init context. Run just once before first scenario starts

         Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
              // End context. Run just once after all scenarios are finished
            }
         });

         initialized = true;
      }
   }
}

I think the context initialization (equivalent to BeforeAll) done in this way is fine. However, although it's working, I'm not sure at all if the AfterAll simulation using Runtime.getRuntime().addShutdownHook() is a good practice.

So, these are my questions:

  • Should I avoid Runtime.getRuntime().addShutdownHook() to implement AfterAll?
  • Are there other better choices to emulate the AfterAll behaviour in cucumber-jvm?

Thanks in advance for the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably a better way would be to use a build tool, like Ant, Maven or Gradle for set-up and tear-down actions, which are part of integration tests.

When using Maven Fail Safe Plug-in, for setting up integration tests. There is the phase pre-integration-test, which is typically used for setting up the database and launch the web-container. Then the integration-tests are run (phase integration-test). And afterwards the phase post-integration-test is run, for shutting down and closing / removing / cleaning up things.

INFO In case the Cucumber tests are run through JUnit, the following might also be worth considering

In case it is simpler, smaller set up stuff, you can have a look at the JUnit @BeforeClass and @AfterClass. Or implement a JUnit @ClassRule, which has it's own before() and after() methods.

@ClassRule
public static ExternalResource resource = new ExternalResource() {
  @Override
  protected void before() throws Throwable {
    myServer.connect();
  }

  @Override
  protected void after() {
    myServer.disconnect();
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...