سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top