Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a spring boot service without running @SpringBootApplication

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?

like image 312
codebrane Avatar asked Oct 12 '18 10:10

codebrane


1 Answers

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;

  ...
}
like image 177
codebrane Avatar answered Oct 18 '22 00:10

codebrane