繁体   English   中英

春天@ContextConfiguration

[英]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);

    }
}

与文件夹/APP/src/main/resources/META-INF/spring/下的文件applicationContext.xml

但似乎没有正确自动装配 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 })

并创建 about 类

@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);
    }
}

上面给出的@Configuration的想法很好用。 但是为此,您必须使用@Configuration注释您的类。 当涉及到离线测试时,即在您的组织中测试用例不在构建时执行时,这不是一个好主意。 在这种情况下,通过@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })将是一个好主意。

要使用此方法,请注意以下事项:

  1. 检查项目的.classpath文件中的类路径。

  2. 如果你不能写applicationContext相对于classpath的路径。

您可以将另一个文件作为applicationContextTest文件夹保存在您的测试用例文件夹中,然后可以使用@ContextConfiguration(locations = { "classpath:applicationContextTest.xml"})

在您的情况下,您应该使用:

@ContextConfiguration(locations = "file:src/main/resources/META-INF/spring/applicationContext.xml")

另一个提示,我看到您在测试环境中使用了生产applicationContext.xml ,恕我直言,这不是一个好习惯,请尝试使用特定的测试环境,例如applicationContext-test.xml ,这样您就可以使用测试上下文而不会伤害您的生产环境。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM