将基于 Spring 3.0.0 java 的 IOC 添加到 JUnit 4.7 测试

发布于 2024-08-21 14:27:24 字数 800 浏览 7 评论 0原文

有一个文档 http://static.springsource.org/spring /docs/2.5.6/reference/testing.html 如何使用 xml 配置向 junit 测试添加 IoC 支持,但我找不到基于 java 的配置示例...

例如,我有 java- based bean:

public class AppConfig
{
    @Bean
    public Test getTest() { return new Test(); }
}

和测试:

@RunWith(SpringJUnit4ClassRunner.class)
public class IocTest
{
    @Autowired
    private Test test;

    @Test
    public void testIoc()
    {
        Assert.assertNotNull(test);
    }
}

我应该添加什么才能在不使用 xml-configs 的情况下在 junit 测试中启用基于 java 的 bean?

通常我使用:

new AnnotationConfigApplicationContext(AppConfig.class);

但它不适用于测试......

There is a doc http://static.springsource.org/spring/docs/2.5.6/reference/testing.html how to add IoC support to junit tests using xml-configuration, but I can not find example for java-based configuration...

For example, I have java-based bean:

public class AppConfig
{
    @Bean
    public Test getTest() { return new Test(); }
}

And test:

@RunWith(SpringJUnit4ClassRunner.class)
public class IocTest
{
    @Autowired
    private Test test;

    @Test
    public void testIoc()
    {
        Assert.assertNotNull(test);
    }
}

What should I add to enable java-based beans to my junit test without using xml-configs?

Normally I use:

new AnnotationConfigApplicationContext(AppConfig.class);

but it does not work for tests...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼波传意 2024-08-28 14:27:24

更新: Spring 3.1将开箱即用地支持它,请参阅Spring 3.1 M2:使用@Configuration类和配置文件进行测试


Spring似乎还不支持这个功能。
不过,它可以很容易地实现:

public class AnnotationConfigContextLoader implements ContextLoader {

    public ApplicationContext loadContext(String... locations) throws Exception {
        Class<?>[] configClasses = new Class<?>[locations.length];
        for (int i = 0; i < locations.length; i++) {
            configClasses[i] = Class.forName(locations[i]);
        }        
        return new AnnotationConfigApplicationContext(configClasses);
    }

    public String[] processLocations(Class<?> c, String... locations) {
        return locations;
    }
}

-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, 
    value = "com.sample.AppConfig")
public class IocTest {
    @Autowired
    TestSerivce service;

    @Test
    public void testIoc()
    {
        Assert.assertNotNull(service.getPredicate());
    }
}

-

@Configuration
public class ApplicationConfig
{
    ...

    @Bean
    public NotExistsPredicate getNotExistsPredicate()
    {
        return new NotExistsPredicate();
    }

    @Bean
    public TestService getTestService() {
        return new TestService();
    }
}

Update: Spring 3.1 will support it out of the box, see Spring 3.1 M2: Testing with @Configuration Classes and Profiles.


It seems to be this feature is not supported by Spring yet.
However, it can be easily implemented:

public class AnnotationConfigContextLoader implements ContextLoader {

    public ApplicationContext loadContext(String... locations) throws Exception {
        Class<?>[] configClasses = new Class<?>[locations.length];
        for (int i = 0; i < locations.length; i++) {
            configClasses[i] = Class.forName(locations[i]);
        }        
        return new AnnotationConfigApplicationContext(configClasses);
    }

    public String[] processLocations(Class<?> c, String... locations) {
        return locations;
    }
}

-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, 
    value = "com.sample.AppConfig")
public class IocTest {
    @Autowired
    TestSerivce service;

    @Test
    public void testIoc()
    {
        Assert.assertNotNull(service.getPredicate());
    }
}

-

@Configuration
public class ApplicationConfig
{
    ...

    @Bean
    public NotExistsPredicate getNotExistsPredicate()
    {
        return new NotExistsPredicate();
    }

    @Bean
    public TestService getTestService() {
        return new TestService();
    }
}
樱花落人离去 2024-08-28 14:27:24

如果您获得空值,则可能没有加载应用程序上下文。

请注意,默认情况下,运行程序从“classpath:/com/test/IocTest-context.xml”加载它(假设 IocTest.java 包是 com.test)

如果不存在,请尝试通过添加来指定它

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "PATH_TO_YOUR_APP_CONTEXT/yourApplicationContext.xml" })
public class IocTest
{
    @Autowired
    private Test test;

    @Test
    public void testIoc()
    {
        Assert.notNull("test is null", test);
    }
}

If you are getting a null value probably it's not loading the application context.

Note that by default it the runner loads it from "classpath:/com/test/IocTest-context.xml" (assuming IocTest.java package is the com.test)

If it is not there try specifying it by adding

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "PATH_TO_YOUR_APP_CONTEXT/yourApplicationContext.xml" })
public class IocTest
{
    @Autowired
    private Test test;

    @Test
    public void testIoc()
    {
        Assert.notNull("test is null", test);
    }
}
晚雾 2024-08-28 14:27:24

一般来说,为什么这不起作用(断言失败):

public class IocTest
{
    @BeforeClass
    public static void initSpringIoc()
    {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        NotExistsPredicate predicate = ctx.getBean(NotExistsPredicate.class);
        LoggerFactory.getLogger(IocTest.class).debug(predicate.toString());
    }

    @Test
    public void testIoc()
    {
        TestService service = new TestService();
        Assert.assertNotNull(service.getPredicate()); // assert fails
    }
}

public class TestService
{
    @Autowired
    private NotExistsPredicate predicate;

    public NotExistsPredicate getPredicate()
    {
        return predicate;
    }
}

日志输出:

1    [main] INFO  org.springframework.context.annotation.AnnotationConfigApplicationContext  - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@e94e92: startup date [Tue Feb 09 15:32:48 EET 2010]; root of context hierarchy
2    [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext@e94e92: org.springframework.beans.factory.support.DefaultListableBeanFactory@a37368: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,applicationConfig]; root of factory hierarchy
33   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
33   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
84   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
87   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
129  [main] DEBUG org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader  - Registering bean definition for @Bean method com.mihailenco.config.ApplicationConfig.getNotExistsPredicate()
133  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
133  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' to allow for resolving potential circular references
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
136  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor' to allow for resolving potential circular references
137  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
142  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
142  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
151  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' to allow for resolving potential circular references
151  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
155  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@86fe26]
164  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@139eeda]
166  [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory  - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@a37368: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,applicationConfig,getNotExistsPredicate]; root of factory hierarchy
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
171  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
171  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'applicationConfig'
172  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'applicationConfig'
174  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'applicationConfig' to allow for resolving potential circular references
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'applicationConfig'
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'getNotExistsPredicate'
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'getNotExistsPredicate'
196  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'applicationConfig'
225  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'getNotExistsPredicate' to allow for resolving potential circular references
232  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'getNotExistsPredicate'
235  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@134a7d8]
235  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'lifecycleProcessor'
237  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'getNotExistsPredicate'
253  [main] DEBUG IocTest  - com.mihailenco.predicate.NotExistsPredicate@982589

Genereally, why this does not work (assert fails):

public class IocTest
{
    @BeforeClass
    public static void initSpringIoc()
    {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        NotExistsPredicate predicate = ctx.getBean(NotExistsPredicate.class);
        LoggerFactory.getLogger(IocTest.class).debug(predicate.toString());
    }

    @Test
    public void testIoc()
    {
        TestService service = new TestService();
        Assert.assertNotNull(service.getPredicate()); // assert fails
    }
}

public class TestService
{
    @Autowired
    private NotExistsPredicate predicate;

    public NotExistsPredicate getPredicate()
    {
        return predicate;
    }
}

Log output:

1    [main] INFO  org.springframework.context.annotation.AnnotationConfigApplicationContext  - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@e94e92: startup date [Tue Feb 09 15:32:48 EET 2010]; root of context hierarchy
2    [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext@e94e92: org.springframework.beans.factory.support.DefaultListableBeanFactory@a37368: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,applicationConfig]; root of factory hierarchy
33   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
33   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
84   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
87   [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
129  [main] DEBUG org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader  - Registering bean definition for @Bean method com.mihailenco.config.ApplicationConfig.getNotExistsPredicate()
133  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
133  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' to allow for resolving potential circular references
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
135  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
136  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor' to allow for resolving potential circular references
137  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
142  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
142  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
151  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' to allow for resolving potential circular references
151  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
155  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@86fe26]
164  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@139eeda]
166  [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory  - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@a37368: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,applicationConfig,getNotExistsPredicate]; root of factory hierarchy
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
166  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
171  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
171  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'applicationConfig'
172  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'applicationConfig'
174  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'applicationConfig' to allow for resolving potential circular references
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'applicationConfig'
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'getNotExistsPredicate'
190  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'getNotExistsPredicate'
196  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'applicationConfig'
225  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Eagerly caching bean 'getNotExistsPredicate' to allow for resolving potential circular references
232  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'getNotExistsPredicate'
235  [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext  - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@134a7d8]
235  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'lifecycleProcessor'
237  [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'getNotExistsPredicate'
253  [main] DEBUG IocTest  - com.mihailenco.predicate.NotExistsPredicate@982589
淡淡的优雅 2024-08-28 14:27:24

这对我有用......

取自 http://www.swiftmind.com/de/2011/06/22/spring-3-1-m2-testing-with-configuration-classes-and-profiles/< /a>

package com.example;

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from the
// OrderServiceConfig class
@ContextConfiguration(classes=OrderServiceConfig.class,
    loader=AnnotationConfigContextLoader.class)
public class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrderService() {
        // test the orderService
    }
}

This is what worked for me...

Taken from http://www.swiftmind.com/de/2011/06/22/spring-3-1-m2-testing-with-configuration-classes-and-profiles/

package com.example;

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from the
// OrderServiceConfig class
@ContextConfiguration(classes=OrderServiceConfig.class,
    loader=AnnotationConfigContextLoader.class)
public class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrderService() {
        // test the orderService
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文