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.
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)
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})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With