Контракт весеннего облака и Зуул

Используя Spring Cloud Dalston, мы создали прокси-сервис, который, конечно же, использует Zuul. Сейчас я пытаюсь добавить тесты Spring Cloud Contract, чтобы убедиться, что наша прокси-служба работает должным образом с точки зрения соблюдения контракта. Что странно, так это то, что я могу отправить запрос и получить обратно код состояния 200, но ожидаемое тело ответа, заголовок типа контента и т. Д. Пусты, и в результате мои тесты терпят неудачу.

Существуют ли дополнительные конфигурации, не указанные в документации Spring Cloud Contract, необходимые для тестирования сервисов, использующих возможности Zuul?


person Keith Bennett    schedule 01.05.2017    source источник
comment
Скорее всего, в случае с Zuul вам понадобится полный контекст Spring, а не просто имитация mvc с некоторыми контроллерами. Вы так ставите тесты?   -  person Marcin Grzejszczak    schedule 02.05.2017
comment
Я настраиваю тесты с помощью DefaultMockMvcBuilder. @Before public void setUp () выдает исключение {DefaultMockMvcBuilder webAppContextSetup = MockMvcBuilders.webAppContextSetup (context); MockMvc build = webAppContextSetup.build (); RestAssuredMockMvc.mockMvc (сборка); }}   -  person Keith Bennett    schedule 02.05.2017
comment
Вы должны использовать явный режим, а не имитировать mvc. Таким образом будут зарегистрированы все фильтры.   -  person Marcin Grzejszczak    schedule 02.05.2017
comment
Есть ли примеры того, как это настроить в GitHub?   -  person Keith Bennett    schedule 02.05.2017
comment
Проверьте это cloud.spring.io/spring-cloud -контракт /   -  person Marcin Grzejszczak    schedule 02.05.2017
comment
Я пробовал это и теперь получаю следующую ошибку: Caused by: org.springframework.boot.context.embedded.tomcat.ConnectorStartFailedException: Connector configured to listen on port 0 failed to start   -  person Keith Bennett    schedule 02.05.2017
comment
Не могли бы вы опубликовать свой образец где-нибудь на Github?   -  person Marcin Grzejszczak    schedule 02.05.2017


Ответы (1)


Вот пример https://github.com/spring-cloud/spring-cloud-contract/issues/450

/**
 * Abstraction of configuration to test contracts with external microservices which are using a zuul-gateway in between.
 *
 * When a provider of data only allows communication through a Zuul-Gateway, a special way to ensure valid contracts is needed.
 * The Goal is to emulate the Zuul-Interception to be able to use the contracts stored within the providing service.
 *
 * F.e.: Consumer-Service consumes the Provider-Service, but the provider can not be called directly.
 * The Consumer-Service calls an URL with a prefix consisting of the name of the gateway ("gateway") and name of the
 * service (in this example "Provider-Service"). For example: http://gateway/provider/path/to/resource.
 * The contract provided by Provider-Service holds only a part of the provided URL (here: "/path/to/resource").
 * The resolution of "gateway" and "provider" is done within this class.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EmbeddedZuulProxy.class,
    properties = {"server.port: 8080",
        "zuul.routes.provider.path: /provider/**",
        "zuul.routes.provider.service-id: provider",
        "zuul.routes.provider.url: http://localhost:9090/" //the url of the provider-stub is at port 9090
    },
    webEnvironment =  WebEnvironment.DEFINED_PORT) //defined port is important! Ribbon points to zuul, which then points to the provider-stub
@AutoConfigureMockMvc
@AutoConfigureJsonTesters
//the stub runs on fixed port 9090, so that zuul can point to it
@AutoConfigureStubRunner(ids = "<group-id>:<artifact-id>:+:stubs:9090")
@DirtiesContext
public abstract class ZuulContractBase {

}

/**
 * Configuration and Setup of an embedded Zuul-Gateway.
 * This way it is possible to use contracts, stored in providing service
 */
@Configuration
@ComponentScan(basePackages = "<path.to.feign.client>") //autowiring feign client
@EnableAutoConfiguration
@EnableZuulProxy
@EnableFeignClients
@RibbonClient(name = "gateway", configuration = SimpleRibbonClientConfiguration.class)
class EmbeddedZuulProxy {

    @Bean
    RouteLocator routeLocator(DiscoveryClient discoveryClient,
                              ZuulProperties zuulProperties) {
        return new DiscoveryClientRouteLocator("/", discoveryClient, zuulProperties);
    }
}

/**
 * Ribbon Load balancer with fixed server list for "simple" pointing to localhost,
 * which holds the mocked zuul-gateway
 *
 * f.e. a call with feign would normally look like:
 * http://gateway/provider/rest/path/to/your/{url}
 * which is mapped to:
 * http://localhost:{zuulport}/provider/rest/path/to/your/{url}
 */
@Configuration
class SimpleRibbonClientConfiguration {

    @Value("${server.port}")
    private Integer zuulPort;

    @Bean
    public ServerList<Server> ribbonServerList() {
        return new StaticServerList<>(new Server("localhost", zuulPort));
    }
}
person Marcin Grzejszczak    schedule 22.12.2017