微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Spring @ContextConfiguration

正在进行一个测试:
import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/meta-inf/spring/applicationContext.xml" })
public class FloorServiceTest {

    @Autowired
    private FloorService floorService;

    @Test
    public void testFloorService() {

        floorService.findById((long)1);

    }
}

使用文件applicationContext.xml下的文件夹/ APP / src / main / resources / meta-inf / spring /

但似乎没有正确地自动装配bean:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.confloorapp.services.FloorServiceTest': Injection of autowired dependencies Failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.confloorapp.services.FloorService com.confloorapp.services.FloorServiceTest.floorService; nested exception is org.springframework.beans.factory.NoSuchBeanDeFinitionException: No qualifying bean of type [com.confloorapp.services.FloorService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

解决方法

尝试
@ContextConfiguration(locations = { "classpath:/meta-inf/spring/applicationContext.xml" })

老实说,我会离开xml并走这条路.
更改

@ContextConfiguration(locations = { "/meta-inf/spring/applicationContext.xml" })

@ContextConfiguration(classes = { FloorServiceTestConfig.class })

并创建关于类

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return new FloorService();
    }
}

这种方式当你需要为类来模拟你的bean时,你没有测试它,如下所示

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return Mockito.mock(FloorService.class);
    }
}

原文地址:https://www.jb51.cc/java/125686.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐