Browse Source

test(train): badge.upgrade RED 契约单测覆盖五边界 TC-1034

liaoxg 1 hour ago
parent
commit
b3e90dde97

+ 308 - 0
train-backend/src/test/java/com/train/service/impl/TrainBadgeUpgradeContractTest.java

@@ -0,0 +1,308 @@
+package com.train.service.impl;
+
+import com.train.common.Result;
+import com.train.entity.TrainBadge;
+import com.train.entity.TrainUserBadge;
+import com.train.mapper.TrainBadgeMapper;
+import com.train.mapper.TrainUserBadgeMapper;
+import com.train.service.BadgeService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Date;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code train.badge.upgrade} 契约级单测(TDD-RED;TC-1034;需求 docs/tdd/SRS.md §3.2 P1-S2 Should)。
+ *
+ * <p>需求口径:已持 T1 徽章且达升档条件(授课量/评分/贡献);When 评定;Then 升级到下一档,
+ * <b>旧档被替换且历史留痕</b>。</p>
+ *
+ * <p>本轮只写测试、不改任何 src/main。说明:本仓后端单模块为 train-backend(无字面量
+ * train-impl / train-contract 模块),徽章域实现为 {@link BadgeService} 与 {@link TrainUserBadge},
+ * 故按同目录既有契约单测惯例落在 train-backend/src/test/java/com/train/service/impl/。</p>
+ *
+ * <p>被测面:{@link BadgeService#grantBadge(Long, String, Long, String)} 是当前唯一的徽章颁发路径
+ * (升档尚未有独立入口,故以其作为行为级对照),以及契约表面反射检查。覆盖五类边界:
+ * replay=true 幂等重放、同键异载荷 C4092、乐观锁冲突 C422、不存在 C404、越权 C403(管理端颁发适用时),
+ * 并校验「旧档替换 + 历史留痕」这一需求判据。</p>
+ *
+ * <p>RED 依据:BadgeService 无任何返回 {@link Result} 的升档入口(无 replay / key / payload / 授权 / 版本入参);
+ * TrainUserBadge 无 version 与历史留痕字段;grantBadge 命中已存在徽章时静默返回 true,既不标记 replay,
+ * 也不替换低档(不调 delete),错误一律为 boolean false 而非带 code 的 Result 信封。</p>
+ *
+ * <p>契约错误码(Result.code):C4092=4092 同幂等键异载荷;C422=422 乐观锁冲突;
+ * C404=404 徽章/档案不存在;C403=403 未授权升档。</p>
+ */
+class TrainBadgeUpgradeContractTest {
+
+    private static final int CODE_SAME_KEY_DIFF_PAYLOAD = 4092;
+    private static final int CODE_VERSION_CONFLICT = 422;
+    private static final int CODE_NOT_FOUND = 404;
+    private static final int CODE_FORBIDDEN = 403;
+
+    private static final Long UID = 990034L;
+    private static final Long ADMIN_ID = 1L;
+    private static final String BADGE_T1 = "lec_t1";
+    private static final String BADGE_T2 = "lec_t2";
+    private static final String MISSING_BADGE = "lec_t9";
+
+    private BadgeService service;
+    private TrainBadgeMapper badgeMapper;
+    private TrainUserBadgeMapper userBadgeMapper;
+
+    @BeforeEach
+    void setUp() {
+        service = new BadgeService();
+        badgeMapper = mock(TrainBadgeMapper.class);
+        userBadgeMapper = mock(TrainUserBadgeMapper.class);
+        ReflectionTestUtils.setField(service, "trainBadgeMapper", badgeMapper);
+        ReflectionTestUtils.setField(service, "trainUserBadgeMapper", userBadgeMapper);
+    }
+
+    private static TrainBadge catalogBadge(String key) {
+        TrainBadge b = new TrainBadge();
+        b.setId(29L);
+        b.setBadgeKey(key);
+        b.setCategory("lecturer");
+        b.setName("讲师徽章");
+        b.setConditionDesc("达升档条件(授课量/评分/贡献)");
+        b.setSort(29);
+        b.setCreatedAt(new Date());
+        return b;
+    }
+
+    // ==================== 基线:当前既有行为(预期通过) ====================
+
+    /** 徽章键不在目录:当前实现返回 false(无 code),作为 C404 缺口的行为对照。 */
+    @Test
+    void unknownBadgeKeyReturnsFalseToday() {
+        when(badgeMapper.selectCount(any())).thenReturn(1L);
+        when(badgeMapper.selectOne(any())).thenReturn(null);
+
+        boolean ok = service.grantBadge(UID, MISSING_BADGE, ADMIN_ID, "升档评定");
+
+        assertEquals(false, ok, "当前实现:徽章键不存在仅返回 boolean false,无 C404 区分");
+    }
+
+    /** 目录命中且用户未持有:颁发成功并写入一条 user_badge(当前实现已覆盖)。 */
+    @Test
+    void knownBadgeKeyInsertsUserBadge() {
+        when(badgeMapper.selectCount(any())).thenReturn(1L);
+        when(badgeMapper.selectOne(any())).thenReturn(catalogBadge(BADGE_T2));
+        when(userBadgeMapper.selectCount(any())).thenReturn(0L);
+
+        boolean ok = service.grantBadge(UID, BADGE_T2, ADMIN_ID, "达升档条件");
+
+        assertEquals(true, ok);
+        verify(userBadgeMapper, times(1)).insert(any(TrainUserBadge.class));
+    }
+
+    // ==================== 契约表面:必须存在带 Result 信封的升档入口 ====================
+
+    /** 升档是状态迁移,契约要求返回 Result 信封以承载 code/data;当前 BadgeService 无任何 Result 方法。 */
+    @Test
+    void upgradeEntryMustReturnResultEnvelope() {
+        Method entry = findUpgradeEntry(2);
+        assertNotNull(entry,
+                "train.badge.upgrade 要求升档入口返回 Result 信封(code/message/data)以承载 "
+                        + CODE_NOT_FOUND + "/" + CODE_FORBIDDEN + " 等契约码;"
+                        + "当前 BadgeService 只有 void/boolean 方法,无任何返回 Result 的升档入口");
+    }
+
+    // ==================== 边界 0:幂等重放 replay=true ====================
+
+    /** 同键同载荷重放须显式标记 replay=true,供调用方区分首次升档与幂等回放,且不得二次写库。 */
+    @Test
+    void replayTrueMustBeSupportedByUpgradeEntry() {
+        Method entry = findUpgradeEntryWithReplay();
+        assertNotNull(entry,
+                "train.badge.upgrade 幂等重放 replay=true 要求升档入口携带 Boolean replay 入参并返回 Result;"
+                        + "当前 grantBadge 命中已持有徽章时静默返回 true,data 无 replay 标记,"
+                        + "调用方无法区分首次升档与重放");
+    }
+
+    // ==================== 边界 1:同键异载荷 C4092 ====================
+
+    /** 同一幂等键携带不同载荷(如升档依据由「评分」变为「授课量」)必须 C4092,禁止静默复用旧结果。 */
+    @Test
+    void sameKeyDifferentPayloadReturnsC4092() {
+        Method entry = findUpgradeEntryWithPayload();
+        assertNotNull(entry,
+                "同一升档幂等键携带不同载荷必须返回 C4092(" + CODE_SAME_KEY_DIFF_PAYLOAD + ") 冲突;"
+                        + "当前无携带 key/payload/replay 的 Result 升档入口,grantBadge 对异载荷仍静默返回 true");
+    }
+
+    // ==================== 边界 2:乐观锁冲突 C422 ====================
+
+    /** 用户徽章记录须有 version 字段支撑并发升档冲突检测(version 不匹配 → C422)。 */
+    @Test
+    void optimisticLockConflictRequiresVersionOnUserBadge() {
+        Field version = findField(TrainUserBadge.class, "version");
+        assertNotNull(version,
+                "并发升档冲突须返回 C422(" + CODE_VERSION_CONFLICT + "):"
+                        + "TrainUserBadge 必须声明 version 字段以支持乐观锁;当前实体无 version,"
+                        + "grantBadge 幂等分支无任何版本校验");
+    }
+
+    // ==================== 边界 3:不存在 C404 ====================
+
+    /** 升档目标徽章不存在(或用户档案不存在)须返回 C404,与系统错误可区分。 */
+    @Test
+    void missingBadgeReturnsC404() {
+        when(badgeMapper.selectCount(any())).thenReturn(1L);
+        when(badgeMapper.selectOne(any())).thenReturn(null);
+
+        boolean ok = service.grantBadge(UID, MISSING_BADGE, ADMIN_ID, "升档评定");
+
+        assertEquals(false, ok, "当前查无仅返回 boolean false");
+
+        Method entry = findUpgradeEntry(2);
+        assertNotNull(entry,
+                "train.badge.upgrade 要求目标徽章/档案不存在时返回 C404(" + CODE_NOT_FOUND + "),"
+                        + "而非 boolean false(500);当前无 Result 升档入口可承载 404 码");
+    }
+
+    // ==================== 边界 4:越权 C403(管理端升档适用时) ====================
+
+    /** 升档须校验操作者身份:非授权调用者必须 C403,当前 grantBadge 直接信任传入 adminId。 */
+    @Test
+    void unauthorizedUpgradeReturnsC403() {
+        Method entry = findAuthorizedUpgradeEntry();
+        assertNotNull(entry,
+                "升档须校验授权(isAdmin/operatorId):未授权调用必须返回 C403(" + CODE_FORBIDDEN + ");"
+                        + "当前 grantBadge 仅接受 Long adminId 且不做角色校验,无 Result + 授权标识的升档入口");
+    }
+
+    // ==================== 需求判据:旧档替换 ====================
+
+    /** 升档到 T2 时须替换旧档 T1(使旧档失效),不允许新旧两档并存为当前档位。 */
+    @Test
+    void upgradeMustReplaceOldTier() {
+        when(badgeMapper.selectCount(any())).thenReturn(1L);
+        when(badgeMapper.selectOne(any())).thenReturn(catalogBadge(BADGE_T2));
+        when(userBadgeMapper.selectCount(any())).thenReturn(0L);
+
+        service.grantBadge(UID, BADGE_T2, ADMIN_ID, "达升档条件 T1→T2");
+
+        verify(userBadgeMapper, times(1)).delete(any());
+    }
+
+    // ==================== 需求判据:历史留痕 ====================
+
+    /** 旧档被替换后须留痕(状态/替换时间字段),否则无法作为合规举证。 */
+    @Test
+    void upgradeMustRetainHistory() {
+        Field history = findField(TrainUserBadge.class, "status");
+        if (history == null) {
+            history = findField(TrainUserBadge.class, "replacedAt");
+        }
+        assertNotNull(history,
+                "「旧档被替换且历史留痕」要求 TrainUserBadge 具备历史留痕字段"
+                        + "(status=superseded 或 replacedAt 之一);当前实体仅有 earnedAt,无替换/历史口径");
+    }
+
+    // ==================== 反射辅助 ====================
+
+    /** 返回 Result、参数不少于 minParams 的升档入口。 */
+    private static Method findUpgradeEntry(int minParams) {
+        for (Method m : BadgeService.class.getMethods()) {
+            String name = m.getName().toLowerCase();
+            if ((name.contains("upgrade") || name.contains("promote") || name.contains("grant"))
+                    && Result.class.isAssignableFrom(m.getReturnType())
+                    && m.getParameterCount() >= minParams) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    /** 返回 Result、带 Boolean replay 入参(且至少有 String 键)的升档入口。 */
+    private static Method findUpgradeEntryWithReplay() {
+        for (Method m : BadgeService.class.getMethods()) {
+            if (!Result.class.isAssignableFrom(m.getReturnType()) || m.getParameterCount() < 3) {
+                continue;
+            }
+            boolean replay = false;
+            boolean key = false;
+            for (Class<?> p : m.getParameterTypes()) {
+                if (Boolean.class.equals(p) || Boolean.TYPE.equals(p)) {
+                    replay = true;
+                }
+                if (String.class.equals(p)) {
+                    key = true;
+                }
+            }
+            if (replay && key) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    /** 返回 Result、带 Boolean replay + String key + Map payload 的升档入口(同键异载荷校验前提)。 */
+    private static Method findUpgradeEntryWithPayload() {
+        for (Method m : BadgeService.class.getMethods()) {
+            if (!Result.class.isAssignableFrom(m.getReturnType()) || m.getParameterCount() < 4) {
+                continue;
+            }
+            boolean replay = false;
+            boolean key = false;
+            boolean payload = false;
+            for (Class<?> p : m.getParameterTypes()) {
+                if (Boolean.class.equals(p) || Boolean.TYPE.equals(p)) {
+                    replay = true;
+                }
+                if (String.class.equals(p)) {
+                    key = true;
+                }
+                if (Map.class.equals(p)) {
+                    payload = true;
+                }
+            }
+            if (replay && key && payload) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    /** 返回 Result、带授权标识(Boolean isAdmin 或 Long operatorId)的升档入口。 */
+    private static Method findAuthorizedUpgradeEntry() {
+        for (Method m : BadgeService.class.getMethods()) {
+            if (!Result.class.isAssignableFrom(m.getReturnType())) {
+                continue;
+            }
+            for (Class<?> p : m.getParameterTypes()) {
+                if (Boolean.class.equals(p) || Boolean.TYPE.equals(p)
+                        || Long.class.equals(p) || Long.TYPE.equals(p)) {
+                    return m;
+                }
+            }
+        }
+        return null;
+    }
+
+    private static Field findField(Class<?> type, String name) {
+        Class<?> c = type;
+        while (c != null) {
+            try {
+                return c.getDeclaredField(name);
+            } catch (NoSuchFieldException ignored) {
+                c = c.getSuperclass();
+            }
+        }
+        return null;
+    }
+}