I'm using Spring Boot in a little PoC, and I'm trying to test a @Bean implementation. I have this code:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(@Value("${db.resetAndLoadOnStartup:true}") boolean resetAndLoadOnStartup,
SequenceIdRepository sequenceRepository,
UserAccountRepository userAccountRepository,
BookRepository bookRepository) {
return args -> {
log.info("Init Application...");
if (resetAndLoadOnStartup) {
fillDBData(sequenceRepository, userAccountRepository, bookRepository);
}
log.info("Aplication initiated!");
};
}
private void fillDBData(SequenceIdRepository sequenceRepository,
UserAccountRepository userAccountRepository,
BookRepository bookRepository) {
// Some code...
}
...
}
How can I unit test this @Bean commandLineRunner? Yeah, maybe I could unit test the 'fillDBData' method (putting protected or with powermock), but I would like to learn if there's a way to test the Spring @Bean "completely".
To test whether Spring MVC controllers are working as expected, use the @WebMvcTest annotation. To test that Spring WebFlux controllers are working as expected, you can use the @WebFluxTest annotation. You can use the @DataJpaTest annotation to test JPA applications.
The @Profile(“test”) annotation is used to configure the class when the Test cases are running. Now, you can write a Unit Test case for Order Service under the src/test/resources package. The complete code for build configuration file is given below.
CommandLineRunner is a simple Spring Boot interface with a run method. Spring Boot will automatically call the run method of all beans implementing this interface after the application context has been loaded.
Here's how you could test with an integration test.
@RunWith(SpringJUnit4ClassRunner.class)
// Or create a test version of Application.class that stubs out services used by the CommandLineRunner
@SpringApplicationConfiguration(classes = Application.class)
public class CommandLineRunnerIntegrationTest {
@Autowired
private CommandLineRunner clr;
@Test
public void thatCommandLineRunnerDoesStuff() throws Exception {
this.clr.run();
// verify changes...
}
}
That being said, my preference would be to create a named service that implements command line runner and then unit test it with all of its dependencies mocked out. In my opinion, it's not critical to test that Spring is going to call the CommandLineRunner bean when the application loads, but that the CommandLineRunner implementation calls other services appropriately.
You can use OutputCapture
to see what you print in the console
@Rule
public OutputCapture outputCapture = new OutputCapture();
in your test method:
String output = this.outputCapture.toString();
assertTrue(output, output.contains("Aplication initiated!"));
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