嗨,我正在尝试Springjunit测试用例…,我需要加载完整的应用程序上下文。但是,junit测试不会初始化完整的应用程序上下文。
测试类别:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) public class MongoDbRepositoryTest { @Value("${spring.datasource.url}") private String databaseUrl; @Inject private ApplicationContext appContext; @Test public void testCRUD() { System.out.println("spring.datasource.url:" + databaseUrl); showBeansIntialised(); assertEquals(1, 1); } private void showBeansIntialised() { System.out.println("BEEEAAANSSSS"); for (String beanName : appContext.getBeanDefinitionNames()) { System.out.println(beanName); } }
输出:
spring.datasource.url:${spring.datasource.url} BEEEAAANSSSS org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.annotation.internalPersistenceAnnotationProcessor org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
主要应用类别注释:
@ComponentScan(basePackages = "com.test") @EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class }) @EnableMongoRepositories("com.test.repository.mongodb") @EnableJpaRepositories("com.test.repository.jpa") @Profile(Constants.SPRING_PROFILE_DEVELOPMENT) public class Application { ...
因此,它应该扫描包com.test中的所有spring bean,并将它们加载到Junit测试用例的applicationcontext中。但是从启动的bean的输出来看,它似乎没有这样做。
您需要按以下方式注释测试类@ActiveProfiles;否则,您的Application配置类将始终被 禁用 。因此,您当前看不到中列出了任何自己的bean ApplicationContext。
@ActiveProfiles
Application
ApplicationContext
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @ActiveProfiles(Constants.SPRING_PROFILE_DEVELOPMENT) public class MongoDbRepositoryTest { /* ... */ }
此外,Application应使用@Configuration别人提到的注释。
@Configuration