Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
使用 Mockito mock JedisPool 避免测试时真实连接 Redis
Co-authored-by: binarywang <1343140+binarywang@users.noreply.github.com>
  • Loading branch information
Copilot and binarywang committed Dec 24, 2025
commit 210d9e55c38ce55ae84ea3a68c1483a838a9d761
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.chanjar.weixin.cp.config.impl;

import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
import redis.clients.jedis.JedisPool;
Expand All @@ -15,40 +16,33 @@ public class WxCpRedisConfigImplTest {
*/
@Test
public void testGetWebhookKeyNoInfiniteRecursion() {
// 创建一个 mock JedisPool(不需要真实连接)
JedisPool jedisPool = new JedisPool("localhost", 6379);

// 使用 Mockito 创建 mock JedisPool,避免真实连接
JedisPool jedisPool = Mockito.mock(JedisPool.class);

WxCpRedisConfigImpl config = new WxCpRedisConfigImpl(jedisPool);

// 测试1: webhookKey 为 null 时应该返回 null,而不是抛出 StackOverflowError
String webhookKey = config.getWebhookKey();
Assert.assertNull(webhookKey, "未设置 webhookKey 时应返回 null");

// 测试2: 通过反射设置 webhookKey,然后验证能够正确获取
// 注意:由于 WxCpRedisConfigImpl 没有提供 setWebhookKey 方法,
// 我们通过反射来设置这个字段以测试 getter 的正确性
try {
WxCpRedisConfigImpl config = new WxCpRedisConfigImpl(jedisPool);

// 测试1: webhookKey 为 null 时应该返回 null,而不是抛出 StackOverflowError
String webhookKey = config.getWebhookKey();
Assert.assertNull(webhookKey, "未设置 webhookKey 时应返回 null");

// 测试2: 通过反射设置 webhookKey,然后验证能够正确获取
// 注意:由于 WxCpRedisConfigImpl 没有提供 setWebhookKey 方法,
// 我们通过反射来设置这个字段以测试 getter 的正确性
java.lang.reflect.Field field = WxCpRedisConfigImpl.class.getDeclaredField("webhookKey");
boolean originalAccessible = field.isAccessible();
field.setAccessible(true);
try {
java.lang.reflect.Field field = WxCpRedisConfigImpl.class.getDeclaredField("webhookKey");
boolean originalAccessible = field.isAccessible();
field.setAccessible(true);
try {
String testWebhookKey = "test-webhook-key-123";
field.set(config, testWebhookKey);
String testWebhookKey = "test-webhook-key-123";
field.set(config, testWebhookKey);

String retrievedKey = config.getWebhookKey();
Assert.assertEquals(retrievedKey, testWebhookKey, "应该返回设置的 webhookKey 值");
} finally {
field.setAccessible(originalAccessible);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("反射设置 webhookKey 失败: " + e.getMessage());
}
} finally {
// 清理资源
if (!jedisPool.isClosed()) {
jedisPool.close();
String retrievedKey = config.getWebhookKey();
Assert.assertEquals(retrievedKey, testWebhookKey, "应该返回设置的 webhookKey 值");
} finally {
field.setAccessible(originalAccessible);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("反射设置 webhookKey 失败: " + e.getMessage());
}
}
}