Search code examples
javatestingannotationstestng

testNG annotation which would equal to "finally" in java?


i don't know if my question was clear, but i am using testNG and i have this:

@Test
public void passengerServiceTest() {
...
}

@AfterTest
public void deleteCreatedPassenger() {
...    
}

I want to execute my deleteCreatedPassenger() method after passengerServiceTest, also, i want that in case of deleteCreatedPassenger fails, passengerServiceTest fails too, in other words, i want that both of them be the same test, so if one them fails, test fails. So i tried with the annotations @AfterTest, @AfterMethod, @AfterClass and all make two tests as "separated" tests. Do you know how to do this? Regards


Solution

  • You don't need annotations to achieve this, since it's exactly what the finally block is intended for:

    @Test
    public void passengerServiceTest() {            
        try {
            //test code 
        } finally {
            deleteCreatedPassenger();
        }
    }
    
    public void deleteCreatedPassenger() {
    ...    
    }
    

    If the delete throws an exception then your service test fails.

    Annotations are useful in certain scenarios, you shouldn't aim to use them over core language constructs.