Skip to content

Instantly share code, notes, and snippets.

@vinnyvoffice
Forked from michaellihs/spring-boot-testing.md
Created October 29, 2017 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinnyvoffice/c37afbfe2152f55e8fba9cb21da04962 to your computer and use it in GitHub Desktop.
Save vinnyvoffice/c37afbfe2152f55e8fba9cb21da04962 to your computer and use it in GitHub Desktop.
Spring Boot Testing

Spring Boot Testing

Using Configuration in Tests

The following snippets loads the application context with the configuration given in TestConfiguration.class

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
public class TestWithContext {

}

Override Configuration in Tests

With the following snippet you can include the configuration from BasicConfiguration and then override it in TestConfiguration

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestWithContext.TestConfiguration.class)
public class TestWithContext {

    @Configuration
    @Import(BasicConfiguration.class)
    public static class TestConfiguration {

        @Bean
        ...

    }
    
}

Enable Component Scan in Tests

If you want to use classes annotated with @Component in your tests, you can use the @ComponentScan(basePackages = "...") annotation:

public class MyTest {
    
    // ...

    @Configuration
    @ComponentScan(basePackages = "ch.lihsmi.spring.amqp.byexample.exchanges.direct")
    public static class TestConfiguration {

        // ...

    }

    @Component
    public static class TestMessageListener {

        // ...

    }
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment