7

I have a spring boot commandline app:

    @SpringBootApplication
    public class TheApplication implements CommandLineRunner {
      public void run(String... args) throws Exception {
        ...
     }
    }

and I'd like to test a @Service that TheApplication uses. Normally this is fine if it's an mvc app where TheApplication does not have any functionality but in this case it's a CommandLineRunner and every time I want to test a @Service, run is called, creating a problem with the tests. I need to annotate the test as the @Service uses @Value to configure itself but these annotations cause the application to start and the run method to be invoked.

Is there a way to run a spring boot test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccessTokenTest {
  ...
}

without TheApplication::run being invoked?

codebrane
  • 4,290
  • 2
  • 18
  • 27
  • 1
    actually, `@SpringBootTest` wakes up the context, so the `.run()` method is invoked. You're free to omit the annotation to test the component without the context though – WildDev Oct 13 '18 at 21:52

1 Answers1

17

Turns out it's fairly easy according to this answer.

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class))
@EnableAutoConfiguration
public class TestApplicationConfiguration {
}

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplicationConfiguration.class)
public class TheTest {
  @Autowired
  TheService theService;

  ...
}
codebrane
  • 4,290
  • 2
  • 18
  • 27