Spring Cloud Contract для AMQP - проблемы с электропроводкой с RabbitTemplate - PullRequest
0 голосов
/ 26 сентября 2019

Я пытаюсь запустить контрактный тест для Spring AMQP с использованием Spring Cloud Contract.Однако я сталкиваюсь с проблемой с автопроводкой RabbitTemplate.В моем Базовом тестовом классе, представленном ниже, автоматическая проводная RabbitTemplate ожидает ConnectionFactory с действительными деталями соединения (хост и порт посредников RabbitMQ).Поскольку тестовые контракты не должны фактически подключаться к брокеру сообщений, в тестовой среде хост и порт не указываются для фабрики соединений.

Я получаю сообщение об ошибке

org.springframework.amqp.AmqpIOException: java.net.UnknownHostException: ${queue.hosts}: nodename nor servname provided, or not known
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:71)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:476)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:614)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:240)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1810)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1784)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:864)

Isшаблон Rabbit должен быть посмеянным?Я попробовал, но даже это не работает.Также пытался передать фиктивную ConnectionFactory фактическому RabbitTemplate, но он пытается получить реальное соединение с фиктивной фабрики.Как обойти проблему, связанную с попыткой установить фактическое соединение?

Базовый тестовый класс

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = QueueConfiguration.class)
@AutoConfigureMessageVerifier
    public class CreateNotificationBase {

    private String message;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Before
    public void setUp() {
        client = new ChangeNotificationClient();
        message = client.buildChangeNotificationMessage();
    }

    protected void onUserCreation() {
    rabbitTemplate.send("change_notification_exchange",
            RoutingKey.CHANGE_NOTIFICATION_KEY.getName(),
            org.springframework.amqp.core.MessageBuilder.withBody(message.getBytes()).build());
    }
}

Определение контракта

label: user_create
input:
  triggeredBy: onUserCreation()
outputMessage:
  sentTo: change_notification_exchange
  body: ''' {"data":["....."jsonapi":{"version":"1.0"}} '''

Автоматически сгенерированный тест

public class CreateTest extends CreateNotificationBase {

    @Inject ContractVerifierMessaging contractVerifierMessaging;
    @Inject ContractVerifierObjectMapper contractVerifierObjectMapper;

    @Test
    public void validate_create() throws Exception {
        // when:
            onUserCreation();

        // then:
            ContractVerifierMessage response = contractVerifierMessaging.receive("change_notification_exchange");
            assertThat(response).isNotNull();
        // and:
            Object responseBody = (contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
                // assertions
            ;
    }

}

...