StubNotFoundException во время настройки контекста

Я пытаюсь добавить весенний облачный контракт в свое приложение jHipster. Это базовое приложение службы Spring Boot Micro. У меня нет проблем с генерацией заглушки для микросервиса номер 1, но когда я пытаюсь ее использовать, я получаю:

org.springframework.cloud.contract.stubrunner.StubNotFoundException: заглушка не найдена для заглушки с тестом нотации

Я использую версию SC-Contract 1.0.1.RELEASE.

jHipster не использует аннотацию @SpringBootApplication, поэтому мне нужно настроить свой контекст с помощью @SpringBootTest(classes=...). В моем случае:

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT, classes=TestApp.class)

Это TestApp.java:

@ComponentScan
@EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class })
@EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class })
@EnableDiscoveryClient
public class TestApp {

    private static final Logger log = LoggerFactory.getLogger(TestApp.class);

    @Inject
    private Environment env;

    /**
     * Initializes Test.
     * <p>
     * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
     * <p>
     * You can find more information on how profiles work with JHipster on <a href="http://jhipster.github.io/profiles/">http://jhipster.github.io/profiles/</a>.
     */
    @PostConstruct
    public void initApplication() {
        log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
        Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
        if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
            log.error("You have misconfigured your application! It should not run " +
            "with both the 'dev' and 'prod' profiles at the same time.");
        }
        if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
            log.error("You have misconfigured your application! It should not" +
            "run with both the 'dev' and 'cloud' profiles at the same time.");
        }
    }

    /**
     * Main method, used to run the application.
     *
     * @param args the command line arguments
     * @throws UnknownHostException if the local host name could not be resolved into an address
     */
    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(TestApp.class);
        DefaultProfileUtil.addDefaultProfile(app);
        Environment env = app.run(args).getEnvironment();
        log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\thttp://localhost:{}\n\t" +
            "External: \thttp://{}:{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        env.getProperty("server.port"),
        InetAddress.getLocalHost().getHostAddress(),
        env.getProperty("server.port"));

        String configServerStatus = env.getProperty("configserver.status");
        log.info("\n----------------------------------------------------------\n\t" +
    "Config Server: \t{}\n----------------------------------------------------------",
        configServerStatus == null ? "Not found or not setup for this application" : configServerStatus);
    }
}

Наконец, это мой тестовый класс (упрощенный):

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT,classes=TestApp.class)
@AutoConfigureStubRunner(ids = "com.mycompany.myapp:article:+:stubs:8080", workOffline = true)
public class ArticleServiceTests {

    private ArticleService service = new ArticleService();

    @Test
    public void shouldExist(){}

}

Трассировки стека :

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webConfigurer': Unsatisfied dependency expressed through field 'hazelcastInstance'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hazelcastInstance' defined in class path resource [com/mycompany/test/config/CacheConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.hazelcast.core.HazelcastInstance]: Factory method 'hazelcastInstance' threw exception; nested exception is org.springframework.cloud.contract.stubrunner.StubNotFoundException: Stub not found for stub with notation [test]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:535)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

Спасибо за помощь !


person julien colin    schedule 16.11.2016    source источник
comment
Вам не нужно использовать @EnableDiscoveryClient для тестового контекста, хотя это может не помочь в решении вашей проблемы.   -  person Gaël Marziou    schedule 16.11.2016
comment
Можете ли вы распечатать всю трассировку стека? А также какую версию SC-Contract вы используете? Также вы уверены, что не передаете собственность stubrunner.ids из своей собственности? Потому что, проанализировав сообщение Stub not found for stub with notation test, я прихожу к выводу, что строковое обозначение вашей заглушки просто test. Как будто вы прошли stubrunner.ids: test, что не имеет смысла.   -  person Marcin Grzejszczak    schedule 16.11.2016
comment
Сообщение отредактировано, пользуюсь версией 1.0.1.RELEASE   -  person julien colin    schedule 16.11.2016
comment
Можете ли вы разместить где-нибудь свое приложение в качестве образца на GitHub? Это действительно очень странно ...   -  person Marcin Grzejszczak    schedule 16.11.2016
comment
Это немного тяжеловато, потому что я использую jhipster, но я опубликую 2 микросервиса. Первый генерирует заглушку, а второй потребляет ее. Но некоторые элементы отсутствуют, если вы хотите запустить приложение как приложение jhipster github.com/colinju/ SC-contract-jhipster-sample   -  person julien colin    schedule 16.11.2016
comment
Я сделал что-то новое, я поместил свой сервис и свой класс в ваш образец (обнаружение мошенничества). Я только что удалил classes=TestApp.class, и все в порядке ... Итак, я полагаю, что конфигурация jhipster вызывает некоторые проблемы с SC-контрактом, и я буду исследовать.   -  person julien colin    schedule 21.11.2016


Ответы (1)


Я нашел, в чем проблема, но пока не знаю, как ее решить.

В jHipster я использую hazelcast, hazelcast использует eureka, а eureka реализует интерфейс DiscoveryClient (ссылка на класс eureka:

person julien colin    schedule 30.11.2016