Skip to content

Instantly share code, notes, and snippets.

@ttekun
Forked from michaellihs/spring-boot-testing.md
Created December 11, 2017 05:09
Show Gist options
  • Save ttekun/3243c7e58874688d7dc8f1bcce0ffe21 to your computer and use it in GitHub Desktop.
Save ttekun/3243c7e58874688d7dc8f1bcce0ffe21 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