0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Create that object with an injected factory instead of new. – tgdavies Jun 01 '23 at 06:37
  • I am assuming what you meant is using "@InjectMocks Dependency2 dependency2" instead of "@Mock Dependency2 dependency2" Tired doing that, however it is resulting in a null pointer exception due to the method dependency2.handle(item) method – Manoj Kommineni Jun 01 '23 at 07:06
  • https://stackoverflow.com/questions/74027324/why-are-my-mocked-methods-not-called-when-executing-a-unit-test provides possible solutions (but not an exact dupe, even though the underlying problem is the same) – knittl Jun 01 '23 at 08:10
  • No, I mean create a factory class, `Dependency2Factory` which has a method `Dependency2 create(Something something)` and inject that into `EventAhandler`. – tgdavies Jun 01 '23 at 12:42

0 Answers0