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?
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;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With