Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I tried:

@RunWith(SpringJUnit4ClassRunner.class) @EnableAutoConfiguration(exclude=CrshAutoConfiguration.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class LikeControllerTest { 

However the CRaSSHD still starts up. While currently it doesn't harm the test, I'd like to disable unnecessary modules during unit testing to speed up and also avoid potential conflicts.

like image 818
Hendy Irawan Avatar asked Nov 02 '14 09:11

Hendy Irawan


People also ask

How do I exclude a class from autoconfiguration in spring boot?

If you find that specific auto-configure classes are being applied that you don't want, you can use the exclude attribute of @EnableAutoConfiguration to disable them. If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead.

What is exclude in spring boot?

If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of @EnableAutoConfiguration to disable them, as shown in the following example: import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org ...

How do you exclude beans?

You need a method with '@Bean' annotation that crate and instance of the class, or annotate the class with '@Componen', '@Service' etc. annotation for annotation scanning to find it ? Does @ComponentScan(excludeFilters = @ComponentScan. Filter(type = FilterType.


2 Answers

Another simple way to exclude the auto configuration classes,

Add below similar configuration to your application.yml file,

--- spring:   profiles: test   autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration 
like image 68
Kane Avatar answered Oct 22 '22 11:10

Kane


Top answers don't point to an even simpler and more flexible solution.

just place a

@TestPropertySource(properties= {"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.example.FooAutoConfiguration"}) @SpringBootTest public class MySpringTest {...} 

annotation above your test class. This means other tests aren't affected by the current test's special case. If there is a configuration affecting most of your tests, then consider using the spring profile instead as the current top answer suggests.

Thanks to @skirsch for encouraging me to upgrade this from a comment to an answer.

like image 22
coderatchet Avatar answered Oct 22 '22 13:10

coderatchet