2017-07-10 35 views
0

我想在我的Spring MVC应用程序中引入JUnit,并且我正在使用Java和xml配置(我的java配置使用xml来自动装入某个变量)的组合来定义我的bean:嵌套的Java和Xml的JUnit弹簧配置

// 1 - 我的测试类

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MvcConfiguration_Test.class) 
@WebAppConfiguration 
public class ClassTest { 
    @Autowired 
    @Qualifier("databaseTest") 
    DataBaseConn conn; 

    @Test 
    public void test() { 
    // do some stuff 
    } 
} 

// 2 - 爪哇配置

@EnableWebMvc 
@Configuration 
@ImportResource({ "applicationContext.xml" }) // this file is in classpath, actually I'm using "classpath:**/applicationContext.xml" but the next step is to move this file in resources/test :) 
public class MvcConfiguration_Test extends MvcConf{ 

    @Autowired 
    String dbName; // defined in applicationContext.xml 

    @Bean 
    public DataBaseConn databaseTest(){ 
    DataBaseConn conn = new DataBaseConn(); 
    conn.addDataSource(dbName, jndi, user, pwd) 
    return conn; 
    } 
} 

// 3 - xml配置 - applicationContext.xml中

<?xml version="1.0" encoding="UTF-8"?> 
<beans ... 
    <context:annotation-config /> 
    <bean id="dbName" class="java.lang.String"> 
     <constructor-arg value="myDb"/> 
    </bean> 
</beans> 

当我启动我的JUnit测试,我得到以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext 
... 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConfiguration_Test': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: java.lang.String package.MvcConfiguration_Test.dbName; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 

的解决方法是丝肮脏的方式分贝的名字: 字符串DBNAME =“MYDB”; 但这不是所需的解决方案:)

PS。我的MVC应用程序被自动装配值correclty(我只从MvcConfiguration删除@ComponentScan("ct.cbi")读取测试配置

+1

自动装配字符串bean对我来说似乎很奇怪。我觉得从属性文件中读取这个值是更好的方法。这当然不是我以前见过的。 – Plog

回答

2

在春季documention提到你不能自动装配字符串:

You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design.

我建议什么是定义在application.properties文件属性,这样你就可以外部化这方面的信息。

你应该看看this进一步的信息。

+0

你说得对,但我的问题与此无关。为了确保这一点,我改变了类型: '@Autowired DbNameBean dbNameBean;' 和在applicationContext.xml中> '<豆ID = “dbNameBean” 类= “package.DbNameBean”> \t \t ' 但仍然有同样的问题。 – NikNik

0

我认为问题可能是您的applicationContext.xml在测试类路径中不可见。您需要将其移至测试/资源以使其正常工作。

但是@Rlarroque在他的回答中提到你真的应该考虑一个属性解决方案来配置你的数据库名称。首先,它可以让你重新配置数据库名称,而无需重建整个应用程序。

+0

你是对的:)但在我以正确的方式配置我的环境之前,我需要让它工作:)正如我在我的问题中所说的,applicationContext.xml位于classpath中。我试图从classpath中移除文件,异常是:'由于:java.io.FileNotFoundException:无法打开ServletContext资源[/applicationContext.xml]'。不过谢谢你的参与。 – NikNik