| 1 | <a id="top"></a> |
| 2 | # Event Listeners |
| 3 | |
| 4 | An event listener is a bit like a reporter, in that it responds to various |
| 5 | reporter events in Catch2, but it is not expected to write any output. |
| 6 | Instead, an event listener performs actions within the test process, such |
| 7 | as performing global initialization (e.g. of a C library), or cleaning out |
| 8 | in-memory logs if they are not needed (the test case passed). |
| 9 | |
| 10 | Unlike reporters, each registered event listener is always active. Event |
| 11 | listeners are always notified before reporter(s). |
| 12 | |
| 13 | To write your own event listener, you should derive from `Catch::TestEventListenerBase`, |
| 14 | as it provides empty stubs for all reporter events, allowing you to |
| 15 | only override events you care for. Afterwards you have to register it |
| 16 | with Catch2 using `CATCH_REGISTER_LISTENER` macro, so that Catch2 knows |
| 17 | about it and instantiates it before running tests. |
| 18 | |
| 19 | Example event listener: |
| 20 | ```cpp |
| 21 | #include <catch2/reporters/catch_reporter_event_listener.hpp> |
| 22 | #include <catch2/reporters/catch_reporter_registrars.hpp> |
| 23 | |
| 24 | class testRunListener : public Catch::EventListenerBase { |
| 25 | public: |
| 26 | using Catch::EventListenerBase::EventListenerBase; |
| 27 | |
| 28 | void testRunStarting(Catch::TestRunInfo const&) override { |
| 29 | lib_foo_init(); |
| 30 | } |
| 31 | }; |
| 32 | |
| 33 | CATCH_REGISTER_LISTENER(testRunListener) |
| 34 | ``` |
| 35 | |
| 36 | _Note that you should not use any assertion macros within a Listener!_ |
| 37 | |
| 38 | [You can find the list of events that the listeners can react to on its |
| 39 | own page](reporter-events.md#top). |
| 40 | |
| 41 | |
| 42 | --- |
| 43 | |
| 44 | [Home](Readme.md#top) |