简体   繁体   中英

Spring Boot Test: How To Use Only Certain Beans?

I have Spring boot applications with bunch of beans. From day to day their amount increase. So all the time I need to mock new beans or tests will fail. So, the question is quite simple: how to force spring boot tests use only few certain beans from application context rather than all ?

So, I figure it out: you need to create class in test package and point test class to run spring from there and you have to define what package need to be scanned for components. For this purpose use prefix scanBasePackages or annotation @ComponentScan ("packageForScan")

@SpringBootApplication(scanBasePackages = {"com.domain.folder1.package1","com.domain.folder1.package2"})
    public static class CustomApplicationRunner {
        public static void main(String[] args) {
            SpringApplication.run(CustomApplicationRunner.class, args);
        }
    }

And in test class you have to point for this class as a main class for running app.

@SpringBootTest(classes = MyTestClass.CustomApplicationRunner.class)
@RunWith(SpringRunner.class)
public class MyTestClass {//tests}

This is how you can include or exclude(with annotation @ComponentScan) any packages from adding to application context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM