Skip to content

Commit 1eeb41d

Browse files
Copilotbinarywang
andcommitted
重构测试代码以消除重复逻辑
Co-authored-by: binarywang <1343140+binarywang@users.noreply.github.com>
1 parent 6a678d1 commit 1eeb41d

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpServiceGetMsgAuditAccessTokenTest.java

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,22 @@ public void testGetMsgAuditAccessToken_Lock() {
9696
}
9797
}
9898

99+
/**
100+
* 检查token是否需要刷新的公共逻辑
101+
*/
102+
private boolean shouldRefreshToken(WxCpConfigStorage storage, boolean forceRefresh) {
103+
return storage.isMsgAuditAccessTokenExpired() || forceRefresh;
104+
}
105+
106+
/**
107+
* 验证会话存档secret是否已配置的公共逻辑
108+
*/
109+
private void validateMsgAuditSecret(String msgAuditSecret) throws WxErrorException {
110+
if (msgAuditSecret == null || msgAuditSecret.trim().isEmpty()) {
111+
throw new WxErrorException("会话存档secret未配置");
112+
}
113+
}
114+
99115
/**
100116
* 创建一个用于测试的BaseWxCpServiceImpl实现,
101117
* 用于测试缓存和过期逻辑
@@ -125,15 +141,13 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException {
125141
@Override
126142
public String getMsgAuditAccessToken(boolean forceRefresh) throws WxErrorException {
127143
// 检查是否需要刷新
128-
if (!getWxCpConfigStorage().isMsgAuditAccessTokenExpired() && !forceRefresh) {
144+
if (!shouldRefreshToken(getWxCpConfigStorage(), forceRefresh)) {
129145
return getWxCpConfigStorage().getMsgAuditAccessToken();
130146
}
131147

132148
// 使用会话存档secret获取access_token
133149
String msgAuditSecret = getWxCpConfigStorage().getMsgAuditSecret();
134-
if (msgAuditSecret == null || msgAuditSecret.trim().isEmpty()) {
135-
throw new WxErrorException("会话存档secret未配置");
136-
}
150+
validateMsgAuditSecret(msgAuditSecret);
137151

138152
// 返回缓存的token(用于测试缓存机制)
139153
return getWxCpConfigStorage().getMsgAuditAccessToken();
@@ -183,15 +197,13 @@ public String getMsgAuditAccessToken(boolean forceRefresh) throws WxErrorExcepti
183197
lock.lock();
184198
try {
185199
// 检查是否需要刷新
186-
if (!getWxCpConfigStorage().isMsgAuditAccessTokenExpired() && !forceRefresh) {
200+
if (!shouldRefreshToken(getWxCpConfigStorage(), forceRefresh)) {
187201
return getWxCpConfigStorage().getMsgAuditAccessToken();
188202
}
189203

190204
// 使用会话存档secret获取access_token
191205
String msgAuditSecret = getWxCpConfigStorage().getMsgAuditSecret();
192-
if (msgAuditSecret == null || msgAuditSecret.trim().isEmpty()) {
193-
throw new WxErrorException("会话存档secret未配置");
194-
}
206+
validateMsgAuditSecret(msgAuditSecret);
195207

196208
// 模拟获取新token并更新配置
197209
getWxCpConfigStorage().updateMsgAuditAccessToken(mockToken, 7200);

0 commit comments

Comments
 (0)