1<a id="top"></a> 2# Event Listeners 3 4A `Listener` is a class you can register with Catch that will then be passed events, 5such as a test case starting or ending, as they happen during a test run. 6`Listeners` are actually types of `Reporters`, with a few small differences: 7 81. Once registered in code they are automatically used - you don't need to specify them on the command line 92. They are called in addition to (just before) any reporters, and you can register multiple listeners. 103. They derive from `Catch::TestEventListenerBase`, which has default stubs for all the events, 11so you are not forced to implement events you're not interested in. 124. You register a listener with `CATCH_REGISTER_LISTENER` 13 14 15## Implementing a Listener 16Simply derive a class from `Catch::TestEventListenerBase` and implement the methods you are interested in, either in 17the main source file (i.e. the one that defines `CATCH_CONFIG_MAIN` or `CATCH_CONFIG_RUNNER`), or in a 18file that defines `CATCH_CONFIG_EXTERNAL_INTERFACES`. 19 20Then register it using `CATCH_REGISTER_LISTENER`. 21 22For example ([complete source code](../examples/210-Evt-EventListeners.cpp)): 23 24```c++ 25#define CATCH_CONFIG_MAIN 26#include "catch.hpp" 27 28struct MyListener : Catch::TestEventListenerBase { 29 30 using TestEventListenerBase::TestEventListenerBase; // inherit constructor 31 32 void testCaseStarting( Catch::TestCaseInfo const& testInfo ) override { 33 // Perform some setup before a test case is run 34 } 35 36 void testCaseEnded( Catch::TestCaseStats const& testCaseStats ) override { 37 // Tear-down after a test case is run 38 } 39}; 40CATCH_REGISTER_LISTENER( MyListener ) 41``` 42 43_Note that you should not use any assertion macros within a Listener!_ 44 45## Events that can be hooked 46 47The following are the methods that can be overridden in the Listener: 48 49```c++ 50// The whole test run, starting and ending 51virtual void testRunStarting( TestRunInfo const& testRunInfo ); 52virtual void testRunEnded( TestRunStats const& testRunStats ); 53 54// Test cases starting and ending 55virtual void testCaseStarting( TestCaseInfo const& testInfo ); 56virtual void testCaseEnded( TestCaseStats const& testCaseStats ); 57 58// Sections starting and ending 59virtual void sectionStarting( SectionInfo const& sectionInfo ); 60virtual void sectionEnded( SectionStats const& sectionStats ); 61 62// Assertions before/ after 63virtual void assertionStarting( AssertionInfo const& assertionInfo ); 64virtual bool assertionEnded( AssertionStats const& assertionStats ); 65 66// A test is being skipped (because it is "hidden") 67virtual void skipTest( TestCaseInfo const& testInfo ); 68``` 69 70More information about the events (e.g. name of the test case) is contained in the structs passed as arguments - 71just look in the source code to see what fields are available. 72 73--- 74 75[Home](Readme.md#top) 76