【发布时间】:2015-03-27 09:21:32
【问题描述】:
我有以下具有不同配置文件的弹簧测试配置:
@Configuration
@ComponentScan (value = {"uk.co.test.ws" })
public class SpringTestConfig
{
@Profile( "local")
@PropertySource( "classpath:/config/local/settings.properties" )
public static class SpringTestConfigLocal
{
@Autowired
private Environment environment ;
@Bean(name= "baseUrl" )
public String setBaseUrl()
{
return environment .getRequiredProperty("baseurl.protocol" )+"://" +environment .getRequiredProperty( "baseurl.host");
}
}
然后创建了一个基类,该基类接受基 url
> @RunWith (SpringJUnit4ClassRunner. class) @ContextConfiguration
> (classes = { SpringTestConfig. class }) public class BaseWsTest {
> @Autowired
> String baseUrl;
然后扩展到其他测试类,如下所示:
public class SampleFTest extends BaseWsTest
{
@Test
public void hello() throws FileNotFoundException, Exception
{
System. out .println("base url: " + baseUrl );
当使用普通的 maven clean install 运行时,测试可以工作,但是如果我通过右键单击该方法来运行它,它会得到一个
Error creating bean with name 'uk.co.test.ws.service.base.SampleFTest': Injection of autowired dependencies failed;
【问题讨论】:
-
“通过右键单击”我猜在某些 IDE 中?如果是这样,您应该在 IDE 中检查此任务的配置。
-
是的,在 eclipse 上,抱歉我忘了提。右键单击运行“JUnit 测试”。它应该有什么配置?我在 vm 参数中添加了 -Dspring.profile.active=local ,但它仍然不起作用..
-
您是否只有消息“自动装配依赖注入失败;”或者你可以看到完整的堆栈跟踪?通常春天也会显示失败的原因。 “找不到豆子”或类似的东西。根据此消息,您可以了解需要在 JUnit 任务的配置中添加什么。
-
嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:java.lang.String uk.co.gamma.gnp.ws.service.base.GnpWsTest.baseUrl;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type of [java.lang.String] found for dependency: 预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
-
这些是完全的例外。我忘了怎么做,所以堆栈跟踪在stackoverflow评论中看起来更清晰抱歉。
标签: java spring testing junit autowired