java - Spring @ContextConfiguration

标签 java spring unit-testing spring-mvc junit4

我正在运行下一个测试:

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

但似乎没有正确地 Autowiring 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);
    }
}

关于java - Spring @ContextConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618039/

相关文章:

java - JERSEY - 将 javax.ws.rs.core.Response 作为 JSON 对象返回,并带有错误 :. .. 或 token :

java - LibGdx (OpenGl ES/Android) - 多次调用 Texture.createGLHandle 返回覆盖它的新创建纹理的 textureid

java - 为什么 list.size()>0 在 Java 中比 list.isEmpty() 慢?

java - org.springframework.web.bind.MissingServletRequestParameterException : Required Date parameter 'startTime' is not present

mysql - 如何验证测试中的项目列表

java - 具有自定义 session 超时的 Spring Security

java - 没有找到 @Autowired 服务依赖类型的合格 Bean

java - 是否有必要将 @JsonIgnoreProperties 放置到 Spring JPA 域中的所有非 JSON 类?

java - DTO 的单元测试

c# - 单元测试 Mvc.Compare 属性错误地返回模型 isValid = true