Browse Source

test(diet): S-cfc-288 diet.nutrition.target 补充边界/默认值 RED 契约单测(TC-P-69-E 精确 400 口径,6红/2绿)

Agnes Agent 1 hour ago
parent
commit
35940c83e1

+ 277 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/DietNutritionTargetBoundaryContractTest.java

@@ -0,0 +1,277 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.UserNutritionProfileController;
+import com.etotem.cfc.entity.UserNutritionProfile;
+import com.etotem.cfc.service.UserNutritionProfileService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.lang.reflect.Field;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * TDD-RED 契约单测补充:精准营养目标设定(能力键 {@code diet.nutrition.target},任务 S-cfc-288 / SC-P-69)。
+ *
+ * <p>本类与已合入主链的 {@code DietNutritionTargetContractTest}(8 例:6 红 / 2 绿)互补,
+ * <b>不重复其断言</b>,只补四条尚未覆盖的 AC 条款:</p>
+ * <ul>
+ *   <li><b>TC-P-69-E 精确边界</b>:目标热量 {@code -100} / {@code 100000} 须返回 400
+ *       且提示「热量需在合理区间」,并不得落库(既有类用 -1 / 999999 且只断言 Runtime 异常,未校验 400 口径);</li>
+ *   <li><b>TC-P-69-E 非数字</b>:目标热量填非数字须返回 Result 400,不得抛原始 NumberFormatException;</li>
+ *   <li><b>宏量营养素目标非法</b>:蛋白/脂肪/碳水/膳食纤维目标负值或超上限同样须拦截;</li>
+ *   <li><b>默认值未实现</b>:未显式设定目标时,档案须提供可用的默认热量目标,
+ *       保证食谱推荐侧(需求变更 §4.7「只读取本能力产出」)始终有目标可用;</li>
+ *   <li><b>正常流落库</b>:合法目标保存后须真正写入档案字段并被服务层保存。</li>
+ * </ul>
+ *
+ * <p><b>需求/设计溯源</b></p>
+ * <ul>
+ *   <li>{@code tests/user-scenarios/应用场景总览.md} SC-P-69;
+ *       {@code tests/test-cases/parent.md} TC-P-69 / TC-P-69-E / TC-P-69-P;</li>
+ *   <li>{@code tests/e2e/api/generated/cases.json} TC-P-69-E(steps: -100 / 100000 / 非数字;
+ *       expected: 400『热量需在合理区间』;非数字 400);</li>
+ *   <li>{@code docs/superpowers/api/API_REFERENCE.md} §4.11 / §4.63.3 —— 载体
+ *       {@code UserNutritionProfileController} 的 {@code /api/nutrition/profile/get|save};</li>
+ *   <li>{@code docs/需求分析/2026-11-22-食材推荐加权规则引擎需求变更.md} §4.7 ——
+ *       食谱按家庭营养目标(热量/蛋白/脂肪/膳食纤维)做组合优化,只读取本能力产出。</li>
+ * </ul>
+ *
+ * <p><b>RED 基线(已核实 origin/cfclub)</b>:{@link UserNutritionProfile} 仅有预算/口味/餐次等偏好字段,
+ * 无任何目标字段;{@link UserNutritionProfileService} 仅有 getByUserId/save,无校验入口;
+ * {@link UserNutritionProfileController#save} 只透传偏好参数,负值/超上限/非数字全部静默通过。
+ * 故本类 6 例契约缺口断言预期失败(红),另 2 例为现状已实现的 GREEN 对照。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:按 TC-P-69-E 补齐目标字段 + 默认目标 + 400 校验 + 不落库语义后自动转绿。
+ * 纯 Mockito / 反射,无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class DietNutritionTargetBoundaryContractTest {
+
+    private static final String KEY = "diet.nutrition.target";
+    private static final String MSG_RANGE = "热量需在合理区间";
+
+    private static final Long SELF = 1L;
+    private static final Long OTHER = 999L;
+
+    private UserNutritionProfileController controller;
+    private UserNutritionProfileService service;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        controller = new UserNutritionProfileController();
+        service = mock(UserNutritionProfileService.class);
+        Field field = UserNutritionProfileController.class.getDeclaredField("service");
+        field.setAccessible(true);
+        field.set(controller, service);
+        // 无历史档案 → 走新建分支(各用例可覆盖)
+        when(service.getByUserId(any())).thenReturn(null);
+    }
+
+    // ==================== 正常流:合法目标保存后应真正写入档案 ====================
+
+    @Test
+    @DisplayName("正常流补充:合法热量/宏量目标保存后应写入档案字段并落库")
+    void validTargets_persistedIntoProfile() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("calorieTarget", 1800);
+        params.put("proteinTarget", 60);
+        params.put("fatTarget", 50);
+        params.put("carbTarget", 200);
+        params.put("fiberTarget", 25);
+
+        Result<String> result = controller.save(SELF, params);
+
+        assertEquals(200, codeOf(result), "[RED/" + KEY + "] 合法目标应保存成功,实际 code=" + codeOf(result));
+        ArgumentCaptor<UserNutritionProfile> captor = ArgumentCaptor.forClass(UserNutritionProfile.class);
+        verify(service).save(captor.capture());
+        UserNutritionProfile saved = captor.getValue();
+        assertTarget(saved, "calorieTarget", 1800);
+        assertTarget(saved, "proteinTarget", 60);
+        assertTarget(saved, "fatTarget", 50);
+        assertTarget(saved, "carbTarget", 200);
+        assertTarget(saved, "fiberTarget", 25);
+    }
+
+    // ==================== 异常流:TC-P-69-E 精确边界(-100 / 100000 / 非数字)====================
+
+    @Test
+    @DisplayName("边界补充:目标热量 -100 应返回 400『热量需在合理区间』且不落库(TC-P-69-E)")
+    void calorieTargetNegative_rejectedWith400() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("calorieTarget", -100);
+
+        Result<String> result = controller.save(SELF, params);
+
+        assertBadRequest(result, "目标热量 -100");
+        verify(service, never()).save(any(UserNutritionProfile.class));
+    }
+
+    @Test
+    @DisplayName("边界补充:目标热量 100000 超上限应返回 400『热量需在合理区间』且不落库(TC-P-69-E)")
+    void calorieTargetOverLimit_rejectedWith400() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("calorieTarget", 100000);
+
+        Result<String> result = controller.save(SELF, params);
+
+        assertBadRequest(result, "目标热量 100000");
+        verify(service, never()).save(any(UserNutritionProfile.class));
+    }
+
+    @Test
+    @DisplayName("异常补充:目标热量非数字应返回 Result 400,不得抛原始 NumberFormatException(TC-P-69-E)")
+    void calorieTargetNonNumeric_rejectedWith400() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("calorieTarget", "abc");
+
+        Result<String> result;
+        try {
+            result = controller.save(SELF, params);
+        } catch (RuntimeException ex) {
+            fail("[RED/" + KEY + "] 目标热量非数字应返回 Result 400,"
+                    + "不得抛原始异常 " + ex.getClass().getSimpleName() + ": " + ex.getMessage());
+            return;
+        }
+
+        assertEquals(400, codeOf(result),
+                "[RED/" + KEY + "] 目标热量非数字应返回 400(TC-P-69-E),实际 code=" + codeOf(result));
+        verify(service, never()).save(any(UserNutritionProfile.class));
+    }
+
+    // ==================== 异常流:宏量营养素目标非法 ====================
+
+    @Test
+    @DisplayName("边界补充:蛋白/脂肪/碳水/膳食纤维目标负值或超上限同样须拦截且不落库")
+    void macroTargetsIllegal_rejected() {
+        String[] illegalNames = {"proteinTarget", "fatTarget", "carbTarget", "fiberTarget"};
+        Object[] illegalValues = {-5, -1, 1000000, 99999};
+        for (int i = 0; i < illegalNames.length; i++) {
+            clearInvocations(service);
+            Map<String, Object> params = new LinkedHashMap<String, Object>();
+            params.put(illegalNames[i], illegalValues[i]);
+
+            Result<String> result = controller.save(SELF, params);
+
+            assertEquals(400, codeOf(result),
+                    "[RED/" + KEY + "] 宏量目标 " + illegalNames[i] + "=" + illegalValues[i]
+                            + " 非法应返回 400(SC-P-69 边界 / TC-P-69-E),实际 code=" + codeOf(result)
+                            + "。当前 save 只透传偏好参数,目标字段被静默忽略。");
+            verify(service, never()).save(any(UserNutritionProfile.class));
+        }
+    }
+
+    // ==================== 默认值未实现:未设定目标时仍应有可用默认目标 ====================
+
+    @Test
+    @DisplayName("默认值补充:未显式设定目标时应回读默认热量目标,保证食谱推荐有目标可用")
+    void unsetCalorieTarget_hasUsableDefault() {
+        UserNutritionProfile existing = new UserNutritionProfile();
+        existing.setUserId(SELF);
+        existing.setMealCount(3);
+        when(service.getByUserId(SELF)).thenReturn(existing);
+
+        Result<UserNutritionProfile> result = controller.get(SELF);
+
+        assertEquals(200, codeOf(result), "[RED/" + KEY + "] 读取营养档案应成功,实际 code=" + codeOf(result));
+        assertNotNull(result.getData(), "[RED/" + KEY + "] 营养档案不应为空。");
+        Object defaultCalorie = fieldValue(result.getData(), "calorieTarget");
+        assertNotNull(defaultCalorie,
+                "[RED/" + KEY + "] 未设定目标时应提供默认热量目标,"
+                        + "否则食谱推荐侧(需求变更 §4.7 只读取本能力产出)无目标可用(默认值未实现)。");
+        assertTrue(defaultCalorie instanceof Number,
+                "[RED/" + KEY + "] 默认热量目标应为数值,实际=" + defaultCalorie);
+        assertTrue(((Number) defaultCalorie).intValue() > 0,
+                "[RED/" + KEY + "] 默认热量目标应为正数,实际=" + defaultCalorie);
+    }
+
+    // ==================== GREEN 对照(现状已实现,如实记录非 RED)====================
+
+    @Test
+    @DisplayName("GREEN 对照:目标保存仍按 @RequestAttribute userId 隔离,不得读写他人档案")
+    void save_scopedToCurrentUserId() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("calorieTarget", 1800);
+
+        controller.save(SELF, params);
+
+        ArgumentCaptor<UserNutritionProfile> captor = ArgumentCaptor.forClass(UserNutritionProfile.class);
+        verify(service).save(captor.capture());
+        assertEquals(SELF, captor.getValue().getUserId(),
+                "[RED/" + KEY + "] 目标档案须归属当前登录用户,实际 userId=" + captor.getValue().getUserId());
+        verify(service, never()).getByUserId(OTHER);
+    }
+
+    @Test
+    @DisplayName("GREEN 对照:既有偏好字段保存行为未被破坏(预算/餐次/口味仍透传)")
+    void existingPreferenceFields_stillPersisted() {
+        Map<String, Object> params = new LinkedHashMap<String, Object>();
+        params.put("budgetMonthly", 1000);
+        params.put("mealCount", 3);
+        params.put("cuisineStyle", "川菜");
+
+        Result<String> result = controller.save(SELF, params);
+
+        assertEquals(200, codeOf(result), "[RED/" + KEY + "] 既有偏好保存不应被破坏,实际 code=" + codeOf(result));
+        ArgumentCaptor<UserNutritionProfile> captor = ArgumentCaptor.forClass(UserNutritionProfile.class);
+        verify(service).save(captor.capture());
+        assertEquals(Integer.valueOf(1000), captor.getValue().getBudgetMonthly());
+        assertEquals(Integer.valueOf(3), captor.getValue().getMealCount());
+        assertEquals("川菜", captor.getValue().getCuisineStyle());
+    }
+
+    // ==================== 辅助 ====================
+
+    private void assertBadRequest(Result<?> result, String what) {
+        assertNotNull(result, "[RED/" + KEY + "] " + what + " 应被拦截,Result 不应为空。");
+        assertEquals(400, codeOf(result),
+                "[RED/" + KEY + "] " + what + " 非法应返回 400(TC-P-69-E),实际 code=" + codeOf(result)
+                        + "。当前 save 无目标校验,非法值静默通过并落库。");
+        assertNotNull(result.getMessage(), "[RED/" + KEY + "] 400 应带提示信息。");
+        assertTrue(result.getMessage().contains(MSG_RANGE),
+                "[RED/" + KEY + "] " + what + " 非法提示应含『" + MSG_RANGE + "』(TC-P-69-E),实际 message="
+                        + result.getMessage());
+    }
+
+    private void assertTarget(UserNutritionProfile profile, String fieldName, int expected) {
+        Object actual = fieldValue(profile, fieldName);
+        assertEquals(Integer.valueOf(expected), actual,
+                "[RED/" + KEY + "] 合法目标 " + fieldName + "=" + expected + " 应写入档案字段(默认值未实现/字段缺失),实际="
+                        + actual);
+    }
+
+    /** 反射读字段;字段不存在返回 null(而非抛异常),保证 RED 为断言失败而非 ERROR。 */
+    private Object fieldValue(Object bean, String name) {
+        if (bean == null) {
+            return null;
+        }
+        for (Field f : bean.getClass().getDeclaredFields()) {
+            if (f.getName().equals(name)) {
+                f.setAccessible(true);
+                try {
+                    return f.get(bean);
+                } catch (IllegalAccessException e) {
+                    return null;
+                }
+            }
+        }
+        return null;
+    }
+
+    private Integer codeOf(Result<?> result) {
+        return result == null ? null : result.getCode();
+    }
+}