java – Spring @ContextConfiguration

前端之家收集整理的这篇文章主要介绍了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.f2er.com/java/125686.html

猜你在找的Java相关文章