2

We have several cucumber step definitions that are modifying the database which would mess up the test afterwards if it doesn't get cleaned up after the test runs. We do this by having a function with the @After annotation that will clean things up.

The problem is that if there's a failure in one of the tests, the function with @After doesn't run, which leaves the database in a bad state.

So the question is, how can I make sure the function with @After always runs, regardless if a test failed or not?

I saw this question, but it's not exactly what I'm trying to do, and the answers don't help.

If it helps, here is part of one of the tests. It's been greatly stripped down, but it has what I think are the important parts.

import static org.hamcrest.MatcherAssert.assertThat;
import cucumber.api.java.After;

public class RunMacroGMUStepDefinition
{
    @Autowired
    protected ClientSOAPRecordkeeperInterface keeper;

    @Given( "^the following Macro exists:$" )
    @Transactional
    public void establishDefaultPatron( final DataTable dataTable )
    {
        for ( final DataTableRow dataTableRow : dataTable.getGherkinRows() )
        {
            // Stuff happens here
            keeper.insert( macroScriptRecord );
        }
    }

    @After( value = "@RunMacroGMU" )
    @Transactional
    public void teardown()
    {
        for ( int i = 0; i < macroScripts.size(); i++ )
        {
            keeper.delete( macroScripts.get( i ) );
        }
    }

    // Part of @Then
    private void compareRecords( final String has, // Other stuff )
    {
        // Stuff happens here
        if ( has.equals( "include" ) )
        {
            assertThat( "No matching data found", foundMatch, equalTo( true ) );
        }
        else
        {
            assertThat( "Found matching data", foundMatch, equalTo( false ) );
        }
    }
}
Community
  • 1
  • 1
Jesse Jashinsky
  • 10,313
  • 6
  • 38
  • 63
  • Maybe you are using junit After annotation (`@org.junit.After`) instead of cucumber After annotation (`@cucumber.api.java.After`). Could you check it? – troig Sep 11 '15 at 12:18
  • We are indeed using `cucumber.api.java.After`. – Jesse Jashinsky Sep 11 '15 at 15:24
  • Humm...so I'm missing something because the default behaviour of cucumber After is always executed after every test, independently if the test has failed. Would it be possible for you to post some code? – troig Sep 11 '15 at 16:08

1 Answers1

0

I personally use Behat (The PHP dist of Cucumber), and we use something like this to take screenshots after a failed test. Did a bit of searching, and found this snippet in Java, that may help with this situation.

@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
    (INSERT FUNCTIONS YOU WOULD LIKE TO RUN AFTER A FAILING TEST HERE)
 }
    driver.close();
}

I hope this helps.

KyleFairns
  • 2,947
  • 1
  • 15
  • 35