How Test a Mqtt Client with Junit without run it but with a mock?

Viewed 471

I have doing a mqtt client with org.springframework.integration.mqtt.core.MqttPaho follow this guide: Spring Mqtt Support and work correctly, I read from a topic and write in another topic.

Now I want test it with Junit5+mockito.. I don't understand well guide in internet.. in particular how mock producer or consumer.. I use configuration for consumer and producer class for example:

@Configuration
public class Consumer {
@Autowired MqttPahoClientFactory mqttClientFactory;
@Bean
public MessageChannel topicChannel(){
    return new DirectChannel();
}

@Bean
public MessageProducer mqttInbound() {
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
            Parameters.MQTT_CLIENT_ID, mqttClientFactory, Parameters.TOPICS[0]);
    adapter.setCompletionTimeout(5000);
    adapter.setConverter(new DefaultPahoMessageConverter());
    adapter.setQos(1);
    adapter.setOutputChannel(topicChannel());
    return adapter;
}
}

and

@Configuration
public class Producer {
    @Autowired MqttPahoClientFactory mqttClientFactory;
    @Bean
    public MessageChannel mqttOutboundChannel(){
        return new DirectChannel();
    }
    @MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
    public interface ProducerGateway {
        void sendToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic);
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                Parameters.MQTT_CLIENT_ID,
                mqttClientFactory);
        messageHandler.setAsync(true);
        messageHandler.setLoggingEnabled(true);
        return messageHandler;
    }
}

@Configuration
public class MqttConfiguration {

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(Parameters.BROKER_URIs);
        options.setUserName(Parameters.MQTT_USERNAME);
        options.setPassword(Parameters.MQTT_PASSWORD.toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

}
0 Answers
Related