избегать вызова CommandLineRunner в junit4 - PullRequest
1 голос
/ 14 февраля 2020

Я работаю над проектом, использующим весеннюю загрузку 2.1.1.RELEASE с junit 4.

Это приложение командной строки, которое полагается на CommandLineRunner в качестве «основного».

Проблема в том, что мне нужно написать модульный тест, использующий некоторые @Autowired вещи

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExcludeCommandLineRunner.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }
}
@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@EnableAutoConfiguration
public class ExcludeCommandLineRunner {
}

, но я не могу избежать того факта, что CommandLineRunner называется .. . как я могу это сделать?

Ответы [ 2 ]

2 голосов
/ 14 февраля 2020

В @ContextConfiguration вы определили свою конфигурацию тестового контекста, которая будет загружена из ExcludeCommandLineRunner Spring TestContext, поэтому она будет выполнена.

@ContextConfiguration(classes = ExcludeCommandLineRunner.class)

Также аннотация @SpringBootTest будет искать основную конфигурацию class (один с @SpringBootApplication (потому что он в свою очередь мета-аннотирован с @SpringBootConfiguration)) и используйте его для запуска контекста приложения Spring. В вашем примере вы явно определили, какой класс использовать для контекста приложения bootstrap.

@SpringBootTest(classes = ExcludeCommandLineRunner.class)

Вы должны использовать одну из приведенных выше аннотаций.

Решение: a) Укажите другой класс ( es) в @ContextConfiguration или b) включить внутренний класс stati c, помеченный @Configuration в классе MyTest, который затем будет использоваться для загрузки тестового контекста. В любом случае вам необходимо удалить аннотацию @SpringBootTest.

@RunWith(SpringRunner.class)                                                
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }

    @Configuration
    public static class TestContextConfiguration {
      // define beans (for example MyService) here
    }

}
2 голосов
/ 14 февраля 2020

В зависимости от того, как вы настроили свой проект, вы можете положиться на Profile, чтобы пропустить CommandLineRunner. Объявите bean-компонент CommandLineRunner с @Profile("!test") и настройте свой тестовый класс для запуска профиля test.

Вот пример, который работает:

@SpringBootApplication
public class SkipCommandLineRunner {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "skipcommandlinerunner");
        SpringApplication.run(SkipCommandLineRunner.class);
    }

    @Bean
    @Profile("!test")
    public CommandLineRunner commandLineRunner() {
        return args -> {
            System.out.println("I am being called");
        };
    }
}
@SpringBootTest
@ActiveProfiles("test")
class SkipCommandLineRunnerTest {

    @Test
    void test() {
        System.out.println("Test is here");
    }
}

2020-02-14 19: 38: 29.525 INFO 41437 --- [main] ossweb.DefaultSecurityFilterChain: создание цепочки фильтров: любой запрос, [org.springframework.security.web.context.request.asyn c. WebAsyncManagerIntegrationFilter@30e143ff, org.springframework.security.web.context. SecurityContextPersistenceFilter@5b59c3d, org.springframework.security.web.header. HeaderWriterFilter@7fd2a67a, org.springframework.security.web.csrf. CsrfFilter@779b4f9c, org.springframework.security. .web.authentication.logout. LogoutFilter@484302ee, org.springframework.security.web.authentication. UsernamePasswordAuthenticationFilter@f0c1ae1, org.springframework.security.web.authentication.ui. DefaultLoginPageGeneratingFilter@252d8df6, org.springframework.security.web.authentication .ui. DefaultLogoutPageGeneratingFilter@452ec287, org.springframework.security.web.authentication. www.BasicAuthenticationFilter@410f53b2, org.springframework.security.web.savedrequest. RequestCacheAwareFilter@46188a89, org.springframework.security.web.servletapi. SecurityContextHolderAwareRequestFilter@37fca349, org .springframework.security.web.authentication. AnonymousAuthenticationFilter@41404aa2, org.springframework.security.web.session. * 102 5 *, org.springframework.security.web.access. ExceptionTranslationFilter@5cb8580, org.springframework.security.web.access.intercept. FilterSecurityInterceptor@4d174189] 2020-02-14 19: 38: 29.586 ИНФОРМАЦИЯ 41437 --- [main] c .zs c .SkipCommandLineRunnerTest: запуск SkipCommandLineRunnerTest через 3,22 секунды (JVM работает для 4,231)

Тест здесь

Вы не видите другой I am being called, который показывает, что CommandLineRunner исключен.

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...