2013-12-05 2 views
0

У меня есть рабочий Спринг приложение компилируется с Maven и развернуто на коте 7.Spring JUnit Test - проблемы Инстанцирования

Я пытаюсь реализую несколько тестов с использованием JUnit 4. Я успешно сделать некоторые испытания для части приложение, но у меня возникает проблема компиляции, когда я хочу протестировать две части, которые использовали внешнюю структуру: Shiro и OIOSAML. Поскольку здесь нет сообщества OIOSAML, я сосредоточусь на сиро, но считаю, что причина проблемы такая же.

Когда я пытаюсь загрузить контекст приложения в тесте JUnit, я получаю ошибки при загрузке (см. Следующий). Похоже, что некоторые зависимости не могут быть загружены/найдены в части фреймворка. Вот некоторые полезные данные:

Shiro исключение:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'authorization' defined in class path resource [test-context.xml]: 
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [myPackage.ShiroAuthorization]: 
Constructor threw exception; nested exception is org.apache.shiro.config.ConfigurationException: 
Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'. 
Please ensure you've specified the fully qualified class name correctly. 
      at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288) 
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035) 
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939) 
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) 
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) 
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) 
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) 
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) 
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) 
      at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) 
      at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) 
      at myPackage.Test.init(Test.java:30) 
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
      at java.lang.reflect.Method.invoke(Unknown Source) 
      at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) 
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
      at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) 
      at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) 
      at org.junit.runners.ParentRunner.run(ParentRunner.java:309) 
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
     Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [myPackage.ShiroAuthorization]: Constructor threw exception; nested exception is org.apache.shiro.config.ConfigurationException: Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'. Please ensure you've specified the fully qualified class name correctly. 
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162) 
      at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:110) 
      at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280) 
      ... 29 more 
     Caused by: org.apache.shiro.config.ConfigurationException: Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'. Please ensure you've specified the fully qualified class name correctly. 
      at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:151) 
      at org.apache.shiro.config.ReflectionBuilder.buildObjects(ReflectionBuilder.java:119) 
      at org.apache.shiro.config.IniSecurityManagerFactory.buildInstances(IniSecurityManagerFactory.java:161) 
      at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:124) 
      at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:102) 
      at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:88) 
      at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:46) 
      at org.apache.shiro.config.IniFactorySupport.createInstance(IniFactorySupport.java:123) 
      at org.apache.shiro.util.AbstractFactory.getInstance(AbstractFactory.java:47) 
      at myPackage.ShiroAuthorization.<init>(ShiroAuthorization.java:31) 
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
      at java.lang.reflect.Constructor.newInstance(Unknown Source) 
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147) 
      ... 31 more 
     Caused by: org.apache.shiro.util.UnknownClassException: Unable to load class named [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] from the thread context, current, or system/application ClassLoaders. All heuristics have been exhausted. Class could not be found. 
      at org.apache.shiro.util.ClassUtils.forName(ClassUtils.java:148) 
      at org.apache.shiro.util.ClassUtils.newInstance(ClassUtils.java:164) 
      at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:144) 
      ... 45 more 

Shiro.ini

... 
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource 
ds.url = jdbc:mysql://******* 
... 
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm 
jdbcRealm.permissionsLookupEnabled=true 
jdbcRealm.dataSource = $ds 
... 
securityManager.realms = $jdbcRealm, 
... 

OIOSAML исключение:

...Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/opensaml/xml/ConfigurationException... 

Test Case

... 
public static ApplicationContext context; 
@BeforeClass 
public static void init() throws Exception { 
    context = new ClassPathXmlApplicationContext("test-context.xml"); 
} 

Я пытался играть с файлом контекста, но ничего не помогает. Что странно, я могу успешно проверить пул соединений tomcat 7, который показывает, что зависимости правильно загружены.

Напоминаю, что все работает, за исключением случаев, когда я хочу проверить его с помощью JUnit.

+0

У вас есть драйвер mySql в вашем пути к классу? Если нет, вероятно, вам нужно добавить его в свой pom.xml – czajek

+0

Что это! ... Когда я его развертываю на tomcat, библиотека загружается из папки WEB-INF/lib. Очевидно, не с JUnit. Сделайте ответ, который я могу принять. Спасибо – Nereis

ответ

1

У вас есть драйвер mySql в вашем пути к классу? Наверное, это проблема.

1

Попробуйте аннотировать тест JUnit класс с помощью:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { 
    "classpath:/test-context.xml" 
}) 

Это загружает ApplicationContext при выполнении ваших тестов JUnit.

Убедитесь, что ваш applicationContext xml находится в вашем пути к классам.

+0

По-прежнему такая же ошибка. – Nereis

+2

Если ваша загрузка Spring верна, я полагаю, ваша проблема в том, что MysqlDataSource не распознается в качестве компонента в вашем приложенииContext ... Попробуйте определить его как компонент в вашем тестовом контексте. Xml –

+0

Действительно, это была проблема, как сказал czajek , Спасибо за вашу помощь. – Nereis