Spring单元测试加载ApplicationContext失败问题求助
Hey there! Let's break down your problem and fix it step by step.
Root Cause Analysis
The core issue here is that you're using WebConfig (a Web MVC layer configuration class annotated with @EnableWebMvc) to test your CustomerDaoImpl—which belongs to the data access layer. Loading a Web MVC config for a DAO test is overkill and causes two big problems:
- Spring tries to initialize web-related beans (like view resolvers, resource handlers, controller mappings) that have no place in a DAO test, leading to unnecessary overhead.
- The
NullPointerExceptionin your error log comes from Spring attempting to detect handler methods (for controllers) but missing required dependencies in the test environment, since you're not running a full servlet container.
Solution 1: Create a Dedicated Test Configuration for DAO Layer
This is the cleanest approach—create a lightweight config that only loads the beans needed for DAO testing:
- Make a
TestConfigclass (place it intest/com.RealEstate/config):
@Configuration @ComponentScan(basePackages = "com.RealEstate.dao") // Only scan DAO components @Import(ApplicationContext.class) // Import your core Spring config (datasource, transactions, etc.) public class TestConfig { // Add test-specific bean configurations here if needed (e.g., an in-memory datasource) }
- Update your test class to use this config instead of
WebConfig:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }) public class CustomerDaoImplTest { @Autowired CustomerDao customerDao; // Remove the redundant @BeforeClass code (you don't need Mockito init for autowired beans) // Your test methods remain the same }
Solution 2: Adjust WebConfig to Exclude Web Components (Not Recommended)
If you must use WebConfig for some reason, modify it to exclude web-specific beans during testing:
@Configuration @EnableWebMvc @ComponentScan(basePackages = "com.RealEstate", excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class), @ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) }) @Import(ApplicationContext.class) public class WebConfig extends WebMvcConfigurerAdapter { // Your existing config code stays the same }
Note: This still loads more beans than necessary for a DAO test, so Solution 1 is preferable.
Extra Tips
- The commented-out
MockitoAnnotations.initMocks(customerDao);in your@BeforeClassis unnecessary—Spring's@Autowiredalready injects the DAO bean for you. Also,@BeforeClassis a static method, so it can't access the non-staticcustomerDaovariable anyway. - Your error log references
AdminDaoImplTest, but you sharedCustomerDaoImplTest—the same fix applies to both, since they're both DAO-layer tests.
内容的提问来源于stack exchange,提问作者OverFlow
相关产品推荐
相关产品推荐

