加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring @ContextConfiguration

发布时间:2020-12-14 16:21:34 所属栏目:Java 来源:网络整理
导读:我正在进行下一个测试: 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.ContextConfigura
我正在进行下一个测试:
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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读