我是spring MVC和JUnit的新手。基本上,我想自动连接服务类,这个类应该在spring上下文中加载。
服务
@Service public class FundService { @Autowired FundDAO fundDAO; /** * @return */ public List getFundDetails(String productId) { return fundDAO.getFundDetails(productId); } }
应用程序-上下文
<beans>
<mvc:annotation-driven />
<context:component-scan base-package="com.test.*" />
</beans>
Junit类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath*:/WEB-INF/application-context.xml"}) public class CompensationServiceTest { @Autowired private FundService fundService; @Test public void verifyGetCompensationList() { System.out.println(fundService == null); } }
在执行测试时,我将得到以下异常跟踪
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.test.admin.service.CompensationServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.admin.service.FundService com.test.admin.service.CompensationServiceTest.fundService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.test.admin.service.FundService] 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)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1064) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.admin.service.FundService com.test.admin.service.CompensationServiceTest.fundService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.test.admin.service.FundService] 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)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.test.admin.service.FundService] 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)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:903) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:772) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:686) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478) ... 28 more
有两种选择:
如果您使用@autowire
,这意味着您正在为测试创建一个应用程序上下文,要实现这一点,有几个步骤;我想告诉你正确的方法,而不是告诉你怎么做。
由于您讨论的是单元测试,这意味着您要测试的类是孤立的,并且注入的依赖项必须是模拟的,下面是一个示例:
类:
@RestController
@RequestMapping(value = "/")
public class CatalogRest {
@Autowired
private CatalogService catalogService;
@Autowired
private LoggedUser loggedUser;
@RequestMapping(value = GET_VIEW_TYPE, method = POST)
public ResponseEntity<List<ViewType>> getViewType() {
List<ViewType> viewTypes = catalogService.getViewType(loggedUser.getUserId());
return new ResponseEntity<List<ViewType>>(viewTypes, HttpStatus.OK);
}
现在的测试是:
@RunWith(MockitoJUnitRunner.class)
public class CatalogRestTest {
@InjectMocks
private CatalogRest subject;
@Mock
private CatalogService catalogService;
@Mock
private LoggedUser loggedUser;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void classAndItsMethodsHaveRequiredAnnotations() throws Exception {
assertTrue(subject.getClass().isAnnotationPresent(RestController.class));
assertTrue(subject.getClass().isAnnotationPresent(RequestMapping.class));
Method getViewTypeMethod = subject.getClass().getMethod("getViewType");
getViewTypeMethod.isAnnotationPresent(RequestMapping.class);
}
@Test
public void getViewType_whenInvoked_returnsAListOfViewTypes() throws Exception {
List<ViewType> viewTypes = Arrays.asList(new ViewType());
when(loggedUser.getUserId()).thenReturn("fake user");
when(catalogService.getViewType(eq("fake user"))).thenReturn(viewTypes);
ResponseEntity<List<ViewType>> result = subject.getViewType();
assertNotNull(result);
assertNotNull(result.getBody());
assertTrue(result.getBody().size() == 1);
verify(catalogService, times(1)).getViewType(eq("fake user"));
}
不要尝试使用spring进行单元测试,它只应用于集成测试
。
首先,WEB-INF
文件夹绝不应该在类路径中;它应该在项目的文件系统中。因此,如果您使用Maven项目结构,该文件夹将相对于项目的根目录(即src/main/webapp/web-inf
)定位。在这种情况下,您需要将该文件夹中的XML配置文件声明为文件系统资源,如下所示:
@contextconfiguration(“file:src/main/webapp/web-inf/application-context.xml”)
其次,如果这是一个测试配置文件,您不应该将其存储在web-inf
下。相反,您应该将其存储在类路径中。按照Maven项目结构,这将是src/test/resources/application-context.xml
,在这种情况下,您将在测试中使用以下声明:
@contextconfiguration(“/application-context.xml”)
或
@contextconfiguration(“classpath:application-context.xml”)
…你喜欢哪一个都行,但请注意它们是等价的。
问候和感谢,
萨姆
9.17 自动驾驶 感知算法实习 一面 自我介绍 ResNet数学原理 one two stage网络代表和区别 SSD yolo Faster RCNN roi pooling和roi algin torch动态图 python装饰器 CaDDN流程 DETR流程 DETR3D deformable attention mmcv中的hook runner机制 反向传播 mAP计算 9.21 二面
聊天机器人:嘿,你介意回答几个问题吗? 顾客:如果是,继续提问/如果不是,向顾客致谢并停止对话。 我在Twilio Autopilot上使用了示例调查机器人,但它实际上没有“if/else”场景。如果Twilio没有它,那么还有其他适合于此的聊天机器人吗?
1. 自我介绍 2. 简单聊了一下项目 召回率 指标 具体实现方案 检测错误的情况 3. C++ 相关 继承封装多态的特点 多态是怎么实现的 有什么好处 虚函数是什么 纯虚函数是什么 析构函数和构造函数 子类实例化的时候 析构和构造的顺序是什么 构造可以使用纯虚函数吗 4. 计算机网络: TCP UDP的区别和应用场景 5.操作系统 进程和线
博世自动驾驶测试一技术面(9月9号):一个Hr,三个技术人员一个是问Git,linux,python;一个问python项目和基础,一个问c++,面了一个小时16分钟。 先来个英文自我,然后就是英文提问,英文提问昨天打电话时没说有英文提问,但是今天添加了,很紧张答的稀烂: 英文问题:我对第一份工作的期望,以及如何定义第一份工作(问了四五个,就记住这一个), 中文: HR:先介绍了一下我的实习经历和
gcc编译 智能指针底层 动态链接和静态链接 ros通信讲解一下,底层机制 手写单例模式代码 代码编译的过程 什么是虚拟内存 互斥锁 加锁的作用 读写锁 项目:怎么检测碰撞 面试官人很好 还给了我学习建议