Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an exception is thrown in the @BeforeEach method, will @AfterEach still run

In my tests, I have data setup (which is a series of different entities) that happens in the @BeforeEach method. I clean up that data in the @AfterEach method. Now if an exception were to be thrown during the creation of any of those entities, will the @AfterEach method run? Currently I have a workaround with a try/catch block in my @BeforeEach method, but it would reduce some code duplication if the @AfterEach method takes care of it for me.

like image 851
Mihir Kothari Avatar asked Oct 24 '25 17:10

Mihir Kothari


1 Answers

So after further testing, the @AfterEach method runs after the @BeforeEach method in the event an exception occurs in the @BeforeEach method. The @BeforeEach method is doing data setup in the DB. It run a series of API calls to create all the data which is persisted in the DB. Then the test runs, followed by the @AfterEach method. If an exception occurs while creating an entity, the @BeforeEach method terminates, the @AfterEach method is invoked which cleans up any created entities.

like image 132
Mihir Kothari Avatar answered Oct 26 '25 07:10

Mihir Kothari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!