2010-02-09 3 views
11

Там является документ http://static.springsource.org/spring/docs/2.5.6/reference/testing.html, как добавить поддержку IoC в JUnit тестов с использованием XML-конфигурации, но я не могу найти пример конфигурации Java на основе ...Добавить Spring 3.0.0 Java на основе МОК JUnit 4.7 тесты

Например, я Java на основе боба:

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); 
    } 
} 

Что я должен добавить, чтобы включить Java на основе бобов на мой JUnit тест без использования XML-конфиги?

Обычно я использую:

new AnnotationConfigApplicationContext(AppConfig.class); 

, но он не работает для испытаний ...

ответ

5

Обновление: Весна 3.1 будет поддерживать ее из коробки, см. Spring 3.1 M2: Testing with @Configuration Classes and Profiles.


Кажется, что эта функция еще не поддерживается весной. Однако, это может быть легко реализовано:

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(); 
    } 
} 
+0

Спасибо, но все равно не могу заставить это работать ... Мой тестовый класс: http://pastebin.com/m4125a931, ApplicationConfig: http : //pastebin.com/m2842d2a1, TestService: http://pastebin.com/m1ac16e48. Затем я нажимаю «Test File» в NetBeans и получаю сообщение об ошибке (assertNotNull) и этот журнал: http://pastebin.com/mad10742. Вы можете что-то посоветовать? –

+0

@Vladimir: Вы не можете просто создать объект с новым именем.Он должен быть получен из контекста. Я добавил пример того, как «TestService» может быть создан с помощью «@ Bean» -аннотированного метода контекста, настроенного аннотацией. – axtavt

+0

Спасибо, axtavt. –

0

Если вы получаете нулевое значение, вероятно, это не нагружает контекст приложения.

Обратите внимание, что по умолчанию бегун загружает его из «путь к классам: /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); 
    } 
} 
+0

Я хочу настроить ApplicationContext без каких-либо конфигураций xml, используя java-конфигурацию. Существует пример (класс AppConfig). –

0

Genereally, почему это не работает (утверждают сбой): выход

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.spring[email protected]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.spring[email protected]e94e92: org.s[email protected]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 [[email protected]26] 
164 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.[email protected]139eeda] 
166 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.s[email protected]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 [[email protected]4a7d8] 
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 - [email protected] 
+1

это не работает, потому что вы его создаете. Но это не должно быть ответом - это должно быть редактирование на ваш вопрос. – Bozho

0

Это то, что работает для меня ...

Взятые из 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 
    } 
} 
Смежные вопросы