【发布时间】:2015-11-30 18:05:44
【问题描述】:
我从事的一个现有项目有一个使用 Java 创建的 Spring bean:
@Configuration
public class BeansConfiguration
{
@Autowired
private Environment environment;
@Bean(name = "edielbean")
public EdielBean edielBean()
{
return new EdielBean();
}
}
现在我想从我的单元测试中访问那个 bean。我的问题类似于How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?,只是我的 bean 不是 XML 而是 Java。
我尝试通过添加这个单元测试(骆驼部分可以忽略):
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class EdielBeanTest extends CamelTestSupport implements ApplicationContextAware {
private ApplicationContext context;
@Override
public String isMockEndpoints() {
// camel
return "*";
}
@Test
public void testSupplierSwitch() throws Exception
{
getMockEndpoint("mock:market-out").expectedMessageCount(1); // camel
System.out.println("beans: "+context.getBeanDefinitionCount());
for (String name: context.getBeanDefinitionNames()) {
System.out.println(name);
}
EdielBean edielBean = (EdielBean)context.getBean("edielbean");
edielBean.startSupplierSwitch(createCustomer(), createOrder(), "54", "43");
assertMockEndpointsSatisfied(); // camel
}
private Customer createCustomer()
{
Customer customer = new Customer();
// .... part omitted
return customer;
}
private Order createOrder() {
Order order = new Order();
// .... part omitted
return order;
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
}
控制台输出显示只有普通的 bean:
...
beans: 6
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessorSep
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
...
测试输出:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'edielbean' is defined
at
....
at com.essent.belgium.ediel.services.EdielBeanTest.testSupplierSwitch(EdielBeanTest.java:42)
at
....
【问题讨论】:
标签: spring junit applicationcontext