0

I am working on Spring Boot application which uses Spring Integration and Mqtt support. Here we have a test to check if the application context is started properly.

class ApplicationTests {

  private @Autowired transient ApplicationContext applicationContext;

  @Test
  void mainMethodTest() {
    Application.main(new String[] {});
    Assertions.assertNotNull(this.applicationContext);
  }
}

but this test will if the Mqtt Broker is not running.

@Bean
  @ConfigurationProperties(prefix = "mqtt")
  public MqttConnectionOptions mqttConnectOptions() {
    return new MqttConnectionOptions();
  }

  @Bean
  @DependsOn("mqttConnectOptions")
  public MessageHandler mqttOutbound() {
    Mqttv5PahoMessageHandler mqttv5PahoMessageHandler =
        new Mqttv5PahoMessageHandler(mqttConnectOptions(), QueueConfigs.CLIENT_ID);
    mqttv5PahoMessageHandler.setAsync(true);
    return mqttv5PahoMessageHandler;
  }

  @Bean
  public IntegrationFlow simulatorReadingsOutFlow() {
    return flow -> flow.handle(mqttOutbound());
  }

tests will fail because the above beans will not be created during the testing without an mqtt broker running in the environment. is there a way to skip the integration flow related beans or mock them during the testing of ApplicationContext.

Priyamal
  • 2,919
  • 2
  • 25
  • 52

1 Answers1

0

One of the solution as @ferrouskid said in the comment is to use @MockBean in your @SpringBootTest:

@MockBean
IntegrationFlow simulatorReadingsOutFlow;

Another solution is to use a @SpringIntegrationTest(noAutoStartup = "mqttOutboundEndpoint") on the class method. But it is going to work only if really use Spring Testing Framework, including or not Spring Boot: https://docs.spring.io/spring-integration/docs/current/reference/html/testing.html#test-context.

However if you do that yourself like that Application.main(new String[] {});, you don't rely on the Spring Testing environment and you just run the whole application outside of the testing scope. Consider to learn more how to test Spring Boot projects: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118