Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only autowire a specific class in JUnit spring test?

I want to write a kind of integration test, but only for a specific class. Which means I want all fields in that class to be automatically wired, but neglect any classes inside the same directory.

Is that possible?

Example:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfig.class})
public class JunitTest {
    @Autowired
    private MyService service;
}

//how to only scan that specific class?
@ComponentScan(basePackageClasses = {MyService.class, MyInjectedService.class})
@Configuration
public class TestConfig {

}


@Service
public class MyService {
    @Autowired
    private MyInjectedService service;
}

Here I want spring to neglect any classes in the same directories as the both basePackageClasses mentioned.

like image 908
membersound Avatar asked Feb 17 '15 10:02

membersound


2 Answers

The classes attributes supported by @ContextConfiguration and @SpringApplicationConfiguration are only required to reference annotated classes; they do not have to be @Configuration classes.

So with that in mind, you should be able to completely forgo component scanning and simply declare your two annotated components as follows:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyService.class, MyInjectedService.class})
public class JUnitTest {
    @Autowired
    private MyService service;

    // ...
}

Having said that, if the above is your goal, it might not make any sense to use Spring Boot's testing support. In other words, if MyService and MyInjectedService do not rely on any features of Spring Boot, you can safely replace @SpringApplicationConfiguration with @ContextConfiguration.

Regards,

Sam (author of the Spring TestContext Framework)

like image 53
Sam Brannen Avatar answered Nov 13 '22 12:11

Sam Brannen


You could make use of filters to customize scanning. There you can extend the ComponentScan Annotation with Attributes like this:

@ComponentScan(
basePackages = {"com.my.package"}, 
useDefaultFilters = false,
includeFilters = {
    @Filter(type = FilterType.ASSIGNABLE_TYPE, value = {MyService.class, MyInjectedService.class})
})
like image 3
sven.kwiotek Avatar answered Nov 13 '22 12:11

sven.kwiotek