简体   繁体   中英

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.

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})
})

You can use @Import annotation. It's more readable and shorter than using the @ComponentScan annotation.

import org.springframework.context.annotation.Import;

@Import(value = {MyService.class, MyInjectedService.class})
public class JUnitTest {
    @Autowired
    private MyService service;

    // ...
}

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