测试类代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/spring.xml")
public class MyTest {
@Test
public void test1(){
System.out.println(1);
}
}
(1)错误1:
报错:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'qrcodeSocketHandler': Unsatisfied dependency expressed through field 'sRedis'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jedisCluster' defined in class path resource [spring/spring-redis.xml]:
Cannot create inner bean 'redis.clients.jedis.HostAndPort#7ea4d397' of type [redis.clients.jedis.HostAndPort] while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'redis.clients.jedis.HostAndPort#7ea4d397' defined in class path resource [spring/spring-redis.xml]:
Unsatisfied dependency expressed through constructor parameter 1: Could not convert argument value of type [java.lang.String] to required type [int]: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "${cluster.port1}"
原因是配置文件中的配置没有加载进来导致的。
我的spring.xml中之前是这样:
<context:property-placeholder location="classpath:*.properties" ignore-unresolvable="true"/>
导致test启动不了
改成
<context:property-placeholder location="classpath*:*.properties" ignore-unresolvable="true"/>
之后就应该成功了
原因:
- 同名资源存在时,classpath: 只从第一个符合条件的classpath中加载资源,而classpath*: 会从所有的classpath中加载符合条件的资源
- classpath*:需要遍历所有的classpath,效率肯定比不上classpath,因此在项目设计的初期就尽量规划好资源文件所在的路径,避免使用classpath*来加载
(2) 错误2:
我的项目比较特殊,出现了一个加载WebMvcConfigurationSupport类时报的错:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException:
No ServletContext set
意思是测试类启动的时候没有加载servletContext容器,
解决方法:在测试类上添加@WebAppConfiguration注释
最后成功启动
成功启动的测试类代码如下:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring/spring.xml") @WebAppConfiguration public class MyTest { @Test public void test1(){ System.out.println(1); } }
参考文章:
1)https://blog.youkuaiyun.com/lebron3v/article/details/80608810
2)https://blog.youkuaiyun.com/liu_gan/article/details/78400627