Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Event Listeners

I need to unit test the functionality of an event listener but I've never done it before and I can't seem to find an example anywhere about it. Does anyone have any suggestions on a good way to go about this?

like image 273
endorphins Avatar asked Jan 07 '14 16:01

endorphins


People also ask

How do you test event listeners?

You can test the event listener does its thing by instantiating the listener, then getting it to handle your event. // Create a listener instance. $listener = app()->make(YourListener::class); // or just app(YourListener::class) // Create an event instance.

What are the event listeners?

An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.

How do you test window addEventListener?

You need to use some concrete event name like for example click - and click on browser page window - eg: window. addEventListener('click', function() { console. log("some_event triggered"); });


1 Answers

There's not much to it, construct the event listener, pass in a mock event, and test.

@Test
public void testEventListener() {
  ActionListener subjectUnderTest = new MyActionListener();
  ActionEvent mockEvent = mock(ActionEvent.class);
  // Or just create a new ActionEvent, e.g. new ActionEvent();
  // setup mock

  subjectUnderTest.actionPerformed(mockEvent);

  // validate
}

Problems can arise when you follow the standard patterns for creating event listeners, where you define an anonymous class that directly interacts with the containing class. However it shouldn't be hard to refactor such a class into its own full class, and pass in any dependencies to the constructor, rather than implicitly from the surrounding class.

like image 80
dimo414 Avatar answered Oct 13 '22 00:10

dimo414