【发布时间】:2021-10-26 01:02:48
【问题描述】:
如何在spring legacy环境下正常运行junit test?
我的 spring 项目被配置为 legacy。
在这里,我尝试进行以下测试。
package com.plx.smtst.itf.controller;
import com.plx.smtst.admin.service.POIInfoService;
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("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class RestApiControllerTest {
// @Setter(onMethod_ = @Autowired)
// private POIInfoServiceImpl poIInfoServiceImpl = new POIInfoServiceImpl();
@Autowired
private POIInfoService poiInfoService;
@Test
public void name() {
System.out.println("hi");
}
}
但它会产生以下错误:
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7ef82753] to prepare test instance [com.plx.smtst.itf.controller.RestApiController3Test@2dd8067 ]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.plx.smtst.itf.controller.RestApiControllerTest': Unsatisfied dependency expressed through field 'poiInfoService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.plx.smtst.admin.service.POIInfoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
@Service 注解存在于 POIInfoService 类中。 然而,test 并不知道 piInfoService。
我的项目中有各种属性,必须在tomcat的vm选项中输入-noverify -Dspring.profiles.active=local -Dfile.encoding=UTF-8才能正常工作。我怀疑。
在boot项目中,即使没有各种设置,测试也能正常运行,但是我不知道如何在这个项目的legacy项目和junit version 4中正常运行测试。 我该如何解决这个问题?
最好的问候!
我尝试添加插件以将 JVM 参数设置为 Tomcat,如下所示
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-noverify -Dspring.profiles.active=local -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
但项目无法正常工作
【问题讨论】:
-
您是否在使用 Spring Boot。
-Dspring.profiles.active=local表示 Spring Boot 属性。那么它是哪一个?此外,您正在使用 XML 文件,如果该 XML 文件没有启用组件扫描,则不会检测到任何内容。所以错误可能在你的root-context.xml。 -
@M. Deinum 感谢您的宝贵建议,我会根据您的建议再试一次!再次感谢
标签: java spring unit-testing junit