我正在为一个REST控制器编写单元测试,这只是一个更大应用程序的一小部分。
我的测试上下文在我的应用程序中无法识别,并且我遇到了以下异常:java.lang.IllegalStateException: Failed to load ApplicationContext
这是我的测试类:
测试RestController
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(locations = "classpath:/META-INF/spring/context-test.xml")
@WebIntegrationTest
public class MyRestControllerTest extends AbstractTransactionnalTest {
@Autowired
private IManager manager;
@Test
// my unit tests
}
问题在于,如果我使用以下应用程序类并使用
classes = Production.class
而不是locations = "classpath:/META-INF/spring/context-test.xml"
,它可以正常工作:@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@EnableScheduling
@ImportResource({ "classpath:/META-INF/spring/context-production.xml" })
public class Production {
// class content
}
我已经阅读了所有类似问题的帖子,我知道它与
@Configuration
和@EnableAutoConfiguration
注释有关,但是当我尝试使用这些注释导入来自context.xml的设置的自定义配置类时,它没有起作用。我理想情况下不希望添加任何配置类,并且只想向我的
test-context.xml
中添加一个bean。是否可能通过在context.xml中添加一个bean或在TestRestController上使用注释来解决此问题?
以下是我的堆栈跟踪:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
... 26 more
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
... 35 more
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:185)
... 39 more
这是我在test-context.xml中用来模拟管理器的bean:
<bean id="IManager"
class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.service.impl.Manager"/>
更新:
我尝试使用一个自定义的管理器模拟,其中数据库被替换为列表。
如果我删除注释@WebIntegrationTest
,应用程序上下文会正确加载,但是由于没有@WebIntegrationTest
注释,服务器未启动而导致另一个异常。
在网络地址上进行GET请求时出现I/O错误:连接被拒绝
我正在运行spring 1.3.7。