Search code examples
javacucumbercucumber-jvmautocloseable

Ensure Autocloseable is closed in Cucumber step definitions


My Cucumber Java step definitions can create AutoCloseable objects, which can acquire external (perhaps scarce) resources. Those objects should have their close() method called when they are no longer needed, to free those resources. How do I ensure that the close() methods are called?

In a non-Cucumber test, I'd use try-with-resources. But that is not possible because there is no single method that spans the execution of a scenario (an AutoCloseable object might be created in a when method, and used in a later then).


Solution

  • One option is to use a method annotated with io.cucumber.java.After to callthe close() method(s). It's not great; we have to rely on Cucmber, rather than Java itelf, doing the right thing.