如何为ConnPoolConfig连接池配置类编写JUnit测试类并解决字段报错
报错原因解析
Cannot locate declared field com.bs.proteo.microservices.channels.sessionmobileadapter.business.openam.resource.ConnPoolConfig.connPoolRouteSize报错的核心原因是:connPoolRouteSize是buildConnectionPool方法的入参,不是ConnPoolConfig类的成员属性,如果你测试代码中用反射直接读取该类的字段,自然找不到对应属性。
正确JUnit测试实现方案
提供两种常用测试方案,可根据测试场景选择:
方案1:纯单元测试(无需启动Spring上下文,执行速度快)
直接实例化配置类,手动传入测试参数调用Bean构造方法,验证返回结果符合预期即可:
import org.apache.http.client.HttpClient; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class ConnPoolConfigTest { private final ConnPoolConfig connPoolConfig = new ConnPoolConfig(); @Test public void testBuildConnectionPoolWithCustomParams() { // 手动传入测试参数,模拟@Value注入的配置值 int testRouteSize = 20; int testPoolSize = 50; int testTtl = 120; int testEvictIdle = 60; int testConnReqTimeout = 3000; int testConnectTimeout = 2000; int testSocketTimeout = 10000; HttpClient httpClient = connPoolConfig.buildConnectionPool( testRouteSize, testPoolSize, testTtl, testEvictIdle, testConnReqTimeout, testConnectTimeout, testSocketTimeout ); // 基础校验:返回的HttpClient实例不为空 assertNotNull(httpClient); // 可按需通过反射读取HttpClient内部的连接池配置,做更细粒度的参数校验 } @Test public void testBuildConnectionPoolWithDefaultParams() { // 传入@Value注解定义的默认值,验证默认场景逻辑正常 HttpClient httpClient = connPoolConfig.buildConnectionPool( 10, 10, 60, 30, 5000, 5000, 30000 ); assertNotNull(httpClient); } }
方案2:Spring环境集成测试(验证配置注入、Bean注册逻辑)
如果需要验证@Value配置注入、Bean注册到Spring上下文的逻辑是否正常,可使用SpringBootTest配合自定义测试配置实现:
import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest(classes = ConnPoolConfig.class) // 注入测试场景专用的配置值,覆盖默认配置 @TestPropertySource(properties = { "login.connectionpool.route.size=25", "login.connectionpool.size=100", "connection.http.timeout.socket=20000" }) public class ConnPoolConfigSpringTest { @Autowired private HttpClient openAmHttpClient; @Test public void testBeanLoadAndConfigInject() { // 校验Bean成功注入到Spring上下文 assertNotNull(openAmHttpClient); // 可按需校验配置是否和@TestPropertySource中设置的测试值一致 } }
注意事项
- 如果你需要做细粒度的参数校验,不要反射读取
ConnPoolConfig的类字段,直接反射返回的HttpClient实例内部的连接池属性即可 ConnPoolConfig无需额外定义类成员变量存储配置参数,方法入参的形式完全符合Spring @Bean方法的注入规范
内容的提问来源于stack exchange,提问作者vyshnavi gadiparthi
相关产品推荐
相关产品推荐

