I have a method which I need to test on Spring Boot using JUnit 5.
@Component
public class EventAhandler implements ApplicationListener<EventA> {
  @Autowired private ApplicationEventPublisher applicationEventPublisher;
  @Autowired private Dependency1 dependency1;
  public void onApplicationEvent(EventA event) {
    Item item = event.getItem();
    Dependency2 dependency2 = new Dependency2(dependency1.getSomething());
    try {
      dependency2.handle(item);
      applicationEventPublisher.publishEvent(new EventB(this, item));
    } catch (Exception e) {
      applicationEventPublisher.publishEvent(
          new EventC(this, item, e.getMessage()));
    }
  }
}
I wrote a test for it as follows:
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class EventAPublisherTest {
  @Autowired private ApplicationEventPublisher applicationEventPublisher;
    @MockBean private Dependency1 dependency1;
    @MockBean private Dependency3 dependency3;
    @Mock private  Dependency2 dependency2;
  @MockBean private EventBHandler EventBHandler;
  @MockBean private EventCHandler EventCHandler;
  @SpyBean private EventTestListener testEventListener;
  private static Item item;
  @BeforeAll
  static void setup() {
    Item item = new Item("test");
  }
  @Test
  public void testEventAListener()
          throws Exception {
      given(this.dependency1.getSomething()).willReturn(dependency3);
      doNothing().when(this.dependency2).handle(item);
    applicationEventPublisher.publishEvent(
        new EventA(this, item));
  }
}
However it throws a null pointer exception for dependency2.handle(item) and it is not mocked or does nothing. Please help me solve this issue.
 
    