我正在运行下一个测试:
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/