我正在运行下一个测试:
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)}
Try
@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })
老实说,我会放弃 xml 并走这条路。
改变
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
to
@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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)