Skip to content

Intercept Exceptions in @BeforeEach for Handling before @AfterEach #3411

@fleytman

Description

@fleytman

Problem:

  1. In JUnit 5, there is a difficulty in handling exceptions that occur in the @BeforeEach method and an inability to intercept them before calling the @AfterEach method, even if an exception occurred in the test.
  2. The @AfterTestExecutionCallback extension allows handling exceptions that occur during the execution of the @Test method (@Test method). However, this extension doesn't work for the @BeforeEach method, thus providing no means to intercept exceptions in this setup phase.

I have a concrete example demonstrating the issue with my code and its output. You can find it here: Code Example and Output.

Consequences:

  1. The inability to intercept and handle exceptions in @BeforeEach before calling the @AfterEach method can lead to redundant logging and capturing screenshots. For instance, if the @AfterEach method involves finalization activities, such as resetting the application or cleaning up data, logs and screenshots might be taken not at the moment of the failure but much later.
  2. In the case of mobile applications, this may result in screenshots being taken not at the moment of the application crash (at the crash site) but at the starting screen or another state of the application after the finalization activities, making it more difficult to identify and analyze the exact cause of the crash.

Desired Solution:

Introduce a new extension or callback method in JUnit 5 that allows handling exceptions in both @BeforeEach and @Test methods before calling @AfterEach.
This proposed solution would enable developers to react to exceptions from @BeforeEach and perform additional actions before calling @AfterEach, enhancing the flexibility of managing resources and logic for each test scenario, as well as ensuring more reliable logging and capturing screenshots at the point of failure.

By implementing this enhancement, JUnit would become an even more powerful tool for developing and managing test scenarios, providing improved error handling, and simplifying the creation of reliable test suites.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions