[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MG20455P54B19S1KDVW1MT":3,"skill-same:01M6MG20455P54B19S1KDVW1MT":50},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":21,"linkOnly":22,"markdownContent":23,"markdownBody":24,"frontMatter":25,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":31,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M6MG20455P54B19S1KDVW1MT","unit-testing",null,"hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1575,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Funit-testing\u002FSKILL.md",[],[18,19,20],"testing","unit testing","unit","2026-11-10 10:12:30",false,"---\n\nname: qa\u002Funit-testing\ndescription: 单元测试方法论，覆盖 AAA 模式、Test Doubles、跨语言示例（JS\u002FTS、Python、Go、Java）、前后端单元测试、边界与属性测试、变异测试\nversion: 1.0.0\nagent: qa\ntype: methodology\nuser-invocable: false\nagent-invocable: true\ndependencies:\n- shared\u002Ftech-stack-detection\n  triggers:\n- 需要编写或审查单元测试时\n- 需要测试纯函数、Service 层、组件、Hook 时\n- 需要确定 Mock 边界时\n  metadata:\n  internal: true\n\n---\n\n# 单元测试方法论\n\n## 单元测试的定义与原则\n\n单元测试验证**最小可测试单元**（函数、方法、类、组件）的行为，隔离外部依赖。\n\n### 核心原则\n\n| 原则     | 说明                                             |\n| -------- | ------------------------------------------------ |\n| **隔离** | 一个测试只验证一个行为，不依赖其他测试或外部系统 |\n| **快速** | 毫秒级执行，全部单元测试应在秒级完成             |\n| **确定** | 相同输入多次运行结果一致，不依赖时间\u002F网络\u002F随机数 |\n| **可读** | 测试代码即文档，命名清晰表达意图                 |\n| **独立** | 测试顺序不影响结果，可任意顺序执行               |\n\n### 什么该做单元测试\n\n| 应该测                   | 不应该测                       |\n| ------------------------ | ------------------------------ |\n| 纯函数 \u002F 工具函数        | 框架内部行为（React 渲染机制） |\n| Service 层业务逻辑       | 第三方库本身                   |\n| 组件渲染与交互（前端）   | 配置文件 \u002F 常量                |\n| Hook 状态逻辑            | 简单的 getter\u002Fsetter           |\n| 校验 \u002F 转换 \u002F 格式化逻辑 | 数据库查询（属于集成测试）     |\n| 状态机 \u002F 状态转换        | 网络请求（属于集成测试）       |\n\n## AAA 模式（Arrange-Act-Assert）\n\n每个单元测试遵循三段式结构：\n\n```typescript\nit('applies 10% discount when total > 100', () => {\n  \u002F\u002F Arrange — 准备测试数据和环境\n  const items = [{ price: 60, quantity: 2 }]; \u002F\u002F total = 120\n  const discount = 0.1;\n\n  \u002F\u002F Act — 执行被测逻辑\n  const result = calculateTotal(items, discount);\n\n  \u002F\u002F Assert — 验证结果\n  expect(result).toBe(108); \u002F\u002F 120 * 0.9\n});\n```\n\n**命名规范**：`[期望行为] when [条件]` 或 `[动作] [结果]`\n\n```typescript\n\u002F\u002F ✅ 好\nit('returns error when email is invalid');\nit('calculates total with discount applied');\n\n\u002F\u002F ❌ 差\nit('should work');\nit('test1');\n```\n\n## Test Doubles（测试替身）\n\n根据用途选择不同的替身类型：\n\n| 类型      | 用途                 | 示例                                    |\n| --------- | -------------------- | --------------------------------------- |\n| **Dummy** | 占位，不被调用       | 传一个空对象满足参数签名                |\n| **Stub**  | 提供预设返回值       | `repo.findById.mockResolvedValue(user)` |\n| **Spy**   | 记录调用信息         | `expect(fn).toHaveBeenCalledWith(arg)`  |\n| **Mock**  | Stub + Spy，验证交互 | `mock.calledWith(...)`                  |\n| **Fake**  | 简化的真实实现       | 内存数据库替代真实 DB                   |\n\n### 何时使用哪种\n\n```typescript\n\u002F\u002F Stub：被测代码需要依赖返回值，但不关心调用细节\njest.mock('..\u002Frepo', () => ({\n  findById: jest.fn().mockResolvedValue({ id: '1', name: 'Alice' }),\n}));\n\n\u002F\u002F Spy：需要验证依赖是否被正确调用\nconst emailSpy = jest.spyOn(emailService, 'send');\nawait userService.register(user);\nexpect(emailSpy).toHaveBeenCalledWith(user.email, expect.any(String));\n\n\u002F\u002F Fake：需要一个可用但简化的实现\nclass FakeCache implements Cache {\n  private store = new Map\u003Cstring, string>();\n  async get(k: string) {\n    return this.store.get(k) ?? null;\n  }\n  async set(k: string, v: string) {\n    this.store.set(k, v);\n  }\n}\n```\n\n## 前端单元测试\n\n### 组件渲染测试\n\n```typescript\n\u002F\u002F Button.test.tsx\nimport { render, screen } from '@testing-library\u002Freact';\nimport userEvent from '@testing-library\u002Fuser-event';\nimport { Button } from '.\u002FButton';\n\ndescribe('Button', () => {\n  it('renders children text', () => {\n    render(\u003CButton>Click me\u003C\u002FButton>);\n    expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();\n  });\n\n  it('calls onClick when clicked', async () => {\n    const handleClick = jest.fn();\n    render(\u003CButton onClick={handleClick}>Click\u003C\u002FButton>);\n\n    await userEvent.click(screen.getByRole('button', { name: 'Click' }));\n\n    expect(handleClick).toHaveBeenCalledTimes(1);\n  });\n\n  it('does not call onClick when disabled', async () => {\n    const handleClick = jest.fn();\n    render(\u003CButton onClick={handleClick} disabled>Click\u003C\u002FButton>);\n\n    await userEvent.click(screen.getByRole('button', { name: 'Click' }));\n\n    expect(handleClick).not.toHaveBeenCalled();\n  });\n\n  it('applies variant styles', () => {\n    const { container } = render(\u003CButton variant=\"primary\">Save\u003C\u002FButton>);\n    expect(container.firstChild).toHaveClass('btn-primary');\n  });\n});\n```\n\n### Hook 测试\n\n```typescript\n\u002F\u002F useCounter.test.ts\nimport { renderHook, act } from '@testing-library\u002Freact';\nimport { useCounter } from '.\u002FuseCounter';\n\ndescribe('useCounter', () => {\n  it('initializes with default value 0', () => {\n    const { result } = renderHook(() => useCounter());\n    expect(result.current.count).toBe(0);\n  });\n\n  it('initializes with provided value', () => {\n    const { result } = renderHook(() => useCounter(10));\n    expect(result.current.count).toBe(10);\n  });\n\n  it('increments count', () => {\n    const { result } = renderHook(() => useCounter());\n    act(() => result.current.increment());\n    expect(result.current.count).toBe(1);\n  });\n\n  it('decrements count but not below 0', () => {\n    const { result } = renderHook(() => useCounter(0));\n    act(() => result.current.decrement());\n    expect(result.current.count).toBe(0); \u002F\u002F 边界：不低于 0\n  });\n\n  it('resets to initial value', () => {\n    const { result } = renderHook(() => useCounter(5));\n    act(() => result.current.increment());\n    act(() => result.current.reset());\n    expect(result.current.count).toBe(5);\n  });\n});\n```\n\n### 工具函数测试\n\n```typescript\n\u002F\u002F formatDate.test.ts\nimport { formatDate, formatCurrency, maskEmail } from '.\u002Fformat';\n\ndescribe('formatDate', () => {\n  it('formats ISO date to YYYY-MM-DD', () => {\n    expect(formatDate('2024-01-15T10:30:00Z')).toBe('2024-01-15');\n  });\n\n  it('handles invalid date gracefully', () => {\n    expect(formatDate('invalid')).toBe('');\n  });\n});\n\ndescribe('maskEmail', () => {\n  it('masks local part of email', () => {\n    expect(maskEmail('alice@example.com')).toBe('a***@example.com');\n  });\n\n  it('handles short local part', () => {\n    expect(maskEmail('ab@example.com')).toBe('a*@example.com');\n  });\n\n  it('returns empty for invalid email', () => {\n    expect(maskEmail('not-an-email')).toBe('');\n  });\n});\n```\n\n## 后端单元测试\n\n### Service 层测试（Mock Repository）\n\n```typescript\n\u002F\u002F userService.test.ts\nimport { UserService } from '.\u002FuserService';\n\n\u002F\u002F Mock 整个 Repository 模块\nconst mockFindById = jest.fn();\nconst mockCreate = jest.fn();\njest.mock('..\u002Frepositories\u002FuserRepository', () => ({\n  UserRepository: jest.fn().mockImplementation(() => ({\n    findById: mockFindById,\n    create: mockCreate,\n  })),\n}));\n\ndescribe('UserService', () => {\n  let service: UserService;\n\n  beforeEach(() => {\n    jest.clearAllMocks();\n    service = new UserService();\n  });\n\n  describe('getById', () => {\n    it('returns user when found', async () => {\n      const user = { id: '1', name: 'Alice', email: 'alice@example.com' };\n      mockFindById.mockResolvedValue(user);\n\n      const result = await service.getById('1');\n\n      expect(result).toEqual(user);\n      expect(mockFindById).toHaveBeenCalledWith('1');\n    });\n\n    it('throws NotFoundError when user does not exist', async () => {\n      mockFindById.mockResolvedValue(null);\n\n      await expect(service.getById('999')).rejects.toThrow('User not found');\n    });\n  });\n\n  describe('create', () => {\n    it('creates user when email is unique', async () => {\n      const data = { name: 'Bob', email: 'bob@example.com' };\n      mockFindById.mockResolvedValue(null); \u002F\u002F 邮箱不存在\n      mockCreate.mockResolvedValue({ id: '2', ...data });\n\n      const result = await service.create(data);\n\n      expect(result).toEqual({ id: '2', ...data });\n      expect(mockCreate).toHaveBeenCalledWith(data);\n    });\n\n    it('throws ConflictError when email exists', async () => {\n      mockFindById.mockResolvedValue({ id: '1', email: 'exists@example.com' });\n\n      await expect(service.create({ name: 'X', email: 'exists@example.com' })).rejects.toThrow(\n        'Email already exists',\n      );\n\n      expect(mockCreate).not.toHaveBeenCalled(); \u002F\u002F 不应调用创建\n    });\n  });\n});\n```\n\n### 纯业务逻辑测试\n\n```typescript\n\u002F\u002F pricing.test.ts\nimport { calculatePrice, applyCoupon } from '.\u002Fpricing';\n\ndescribe('calculatePrice', () => {\n  it('sums item prices', () => {\n    const items = [\n      { price: 100, quantity: 2 },\n      { price: 50, quantity: 1 },\n    ];\n    expect(calculatePrice(items)).toBe(250);\n  });\n\n  it('returns 0 for empty items', () => {\n    expect(calculatePrice([])).toBe(0);\n  });\n\n  it('throws on negative quantity', () => {\n    expect(() => calculatePrice([{ price: 10, quantity: -1 }])).toThrow(\n      'Quantity must be positive',\n    );\n  });\n});\n\ndescribe('applyCoupon', () => {\n  const basePrice = 100;\n\n  it('applies percentage discount', () => {\n    expect(applyCoupon(basePrice, { type: 'percent', value: 20 })).toBe(80);\n  });\n\n  it('applies fixed amount discount', () => {\n    expect(applyCoupon(basePrice, { type: 'fixed', value: 30 })).toBe(70);\n  });\n\n  it('does not go below 0', () => {\n    expect(applyCoupon(10, { type: 'fixed', value: 100 })).toBe(0);\n  });\n\n  it('caps percentage at 100', () => {\n    expect(applyCoupon(basePrice, { type: 'percent', value: 150 })).toBe(0);\n  });\n});\n```\n\n## Python 单元测试\n\n```python\n# tests\u002Funit\u002Ftest_pricing.py\nimport pytest\nfrom app.pricing import calculate_price, apply_coupon\n\nclass TestCalculatePrice:\n    def test_sums_item_prices(self):\n        items = [{\"price\": 100, \"quantity\": 2}, {\"price\": 50, \"quantity\": 1}]\n        assert calculate_price(items) == 250\n\n    def test_empty_items_returns_zero(self):\n        assert calculate_price([]) == 0\n\n    def test_negative_quantity_raises(self):\n        with pytest.raises(ValueError, match=\"Quantity must be positive\"):\n            calculate_price([{\"price\": 10, \"quantity\": -1}])\n\n\nclass TestApplyCoupon:\n    @pytest.mark.parametrize(\"coupon_type,value,expected\", [\n        (\"percent\", 20, 80),\n        (\"fixed\", 30, 70),\n        (\"percent\", 100, 0),\n        (\"percent\", 150, 0),  # cap at 0\n    ])\n    def test_applies_discount(self, coupon_type, value, expected):\n        coupon = {\"type\": coupon_type, \"value\": value}\n        assert apply_coupon(100, coupon) == expected\n\n    def test_does_not_go_below_zero(self):\n        assert apply_coupon(10, {\"type\": \"fixed\", \"value\": 100}) == 0\n```\n\n### Python Mock 示例\n\n```python\n# tests\u002Funit\u002Ftest_user_service.py\nfrom unittest.mock import Mock, patch\nfrom app.services.user_service import UserService\n\nclass TestUserService:\n    def test_get_by_id_returns_user(self):\n        mock_repo = Mock()\n        mock_repo.find_by_id.return_value = {\"id\": \"1\", \"name\": \"Alice\"}\n        service = UserService(mock_repo)\n\n        result = service.get_by_id(\"1\")\n\n        assert result[\"name\"] == \"Alice\"\n        mock_repo.find_by_id.assert_called_once_with(\"1\")\n\n    def test_get_by_id_raises_when_not_found(self):\n        mock_repo = Mock()\n        mock_repo.find_by_id.return_value = None\n        service = UserService(mock_repo)\n\n        with pytest.raises(ValueError, match=\"User not found\"):\n            service.get_by_id(\"999\")\n```\n\n## Go 单元测试\n\n```go\n\u002F\u002F pricing_test.go\npackage pricing\n\nimport \"testing\"\n\nfunc TestCalculatePrice(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\titems []Item\n\t\twant  int\n\t}{\n\t\t{\"sums prices\", []Item{{Price: 100, Qty: 2}, {Price: 50, Qty: 1}}, 250},\n\t\t{\"empty items\", []Item{}, 0},\n\t\t{\"single item\", []Item{{Price: 10, Qty: 3}}, 30},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := CalculatePrice(tt.items)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"CalculatePrice() = %d, want %d\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCalculatePriceNegativeQty(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"expected panic for negative quantity\")\n\t\t}\n\t}()\n\tCalculatePrice([]Item{{Price: 10, Qty: -1}})\n}\n```\n\n### Go 接口 Mock\n\n```go\n\u002F\u002F user_service_test.go\npackage service\n\nimport (\n\t\"testing\"\n\t\"github.com\u002Fstretchr\u002Ftestify\u002Fassert\"\n\t\"github.com\u002Fstretchr\u002Ftestify\u002Fmock\"\n)\n\n\u002F\u002F Mock Repository\ntype MockUserRepo struct {\n\tmock.Mock\n}\n\nfunc (m *MockUserRepo) FindByID(id string) (*User, error) {\n\targs := m.Called(id)\n\tif args.Get(0) == nil {\n\t\treturn nil, args.Error(1)\n\t}\n\treturn args.Get(0).(*User), args.Error(1)\n}\n\nfunc TestUserService_GetByID(t *testing.T) {\n\tmockRepo := new(MockUserRepo)\n\tmockRepo.On(\"FindByID\", \"1\").Return(&User{ID: \"1\", Name: \"Alice\"}, nil)\n\n\tservice := NewUserService(mockRepo)\n\tuser, err := service.GetByID(\"1\")\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"Alice\", user.Name)\n\tmockRepo.AssertExpectations(t)\n}\n```\n\n## Java 单元测试\n\n```java\n\u002F\u002F PricingTest.java\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.CsvSource;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass PricingTest {\n\n    @Test\n    void sumsItemPrices() {\n        var items = List.of(\n            new Item(100, 2),\n            new Item(50, 1)\n        );\n        assertEquals(250, Pricing.calculatePrice(items));\n    }\n\n    @ParameterizedTest\n    @CsvSource({\n        \"percent, 20, 80\",\n        \"fixed, 30, 70\",\n        \"percent, 100, 0\",\n    })\n    void appliesDiscount(String type, int value, int expected) {\n        var coupon = new Coupon(type, value);\n        assertEquals(expected, Pricing.applyCoupon(100, coupon));\n    }\n\n    @Test\n    void throwsOnNegativeQuantity() {\n        var items = List.of(new Item(10, -1));\n        assertThrows(IllegalArgumentException.class,\n            () -> Pricing.calculatePrice(items));\n    }\n}\n```\n\n### Java Mockito 示例\n\n```java\n\u002F\u002F UserServiceTest.java\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.junit.jupiter.MockitoExtension;\nimport static org.mockito.Mockito.*;\nimport static org.junit.jupiter.api.Assertions.*;\n\n@ExtendWith(MockitoExtension.class)\nclass UserServiceTest {\n\n    @Mock\n    private UserRepository userRepository;\n\n    @InjectMocks\n    private UserService userService;\n\n    @Test\n    void getByIdReturnsUser() {\n        var user = new User(\"1\", \"Alice\");\n        when(userRepository.findById(\"1\")).thenReturn(Optional.of(user));\n\n        var result = userService.getById(\"1\");\n\n        assertEquals(\"Alice\", result.getName());\n        verify(userRepository).findById(\"1\");\n    }\n\n    @Test\n    void getByIdThrowsWhenNotFound() {\n        when(userRepository.findById(\"999\")).thenReturn(Optional.empty());\n\n        assertThrows(UserNotFoundException.class,\n            () -> userService.getById(\"999\"));\n    }\n}\n```\n\n## 边界值与特殊情况\n\n单元测试必须覆盖边界：\n\n| 边界类型          | 示例                              |\n| ----------------- | --------------------------------- |\n| **空值**          | 空字符串、空数组、null、undefined |\n| **零值**          | 数量为 0、金额为 0                |\n| **最小值\u002F最大值** | 字符串最大长度、数值上下限        |\n| **负数**          | 负数数量、负数金额                |\n| **类型边界**      | 整数溢出、浮点数精度              |\n| **日期时间**      | 闰年、时区、夏令时、跨年          |\n| **集合边界**      | 单元素、刚好达到上限、超过上限    |\n\n```typescript\ndescribe('pagination', () => {\n  it('returns first page when page is 1', () => {\n    expect(paginate(items, 1, 10)).toEqual(items.slice(0, 10));\n  });\n\n  it('returns empty array when page exceeds total', () => {\n    expect(paginate([1, 2, 3], 10, 10)).toEqual([]);\n  });\n\n  it('clamps pageSize to max', () => {\n    expect(paginate(items, 1, 1000).length).toBeLessThanOrEqual(100);\n  });\n\n  it('handles page 0 as page 1', () => {\n    expect(paginate(items, 0, 10)).toEqual(paginate(items, 1, 10));\n  });\n});\n```\n\n## 错误与异常测试\n\n```typescript\ndescribe('error handling', () => {\n  it('throws custom error with code', () => {\n    expect(() => validateEmail('invalid')).toThrow(\n      expect.objectContaining({ code: 'INVALID_EMAIL' }),\n    );\n  });\n\n  it('rejects promise with typed error', async () => {\n    await expect(service.delete('not-owner-id')).rejects.toMatchObject({\n      code: 'FORBIDDEN',\n      status: 403,\n    });\n  });\n\n  it('does not throw for valid input', () => {\n    expect(() => validateEmail('a@b.com')).not.toThrow();\n  });\n});\n```\n\n## 属性测试（Property-Based Testing）\n\n对纯函数，用随机生成的输入验证不变量：\n\n```typescript\n\u002F\u002F 使用 fast-check\nimport fc from 'fast-check';\n\ndescribe('reverse function (property test)', () => {\n  it('reverse of reverse equals original', () => {\n    fc.assert(\n      fc.property(fc.array(fc.integer()), (arr) => {\n        expect(reverse(reverse(arr))).toEqual(arr);\n      }),\n    );\n  });\n\n  it('reverse preserves length', () => {\n    fc.assert(\n      fc.property(fc.array(fc.integer()), (arr) => {\n        expect(reverse(arr)).toHaveLength(arr.length);\n      }),\n    );\n  });\n});\n```\n\n## 变异测试（Mutation Testing）\n\n变异测试验证测试的有效性：故意修改源代码（变异），检查测试是否能捕获。\n\n```bash\n# Node.js (Stryker)\nnpx stryker run\n\n# Python (mutmut)\nmutmut run\n\n# Go\ngo test -run TestMutate -v\n```\n\n**变异算子**：\n- `a + b` → `a - b`\n- `a > b` → `a >= b`\n- `&&` → `||`\n- `return x` → `return 0` \u002F `return null`\n\n**变异得分** = 被杀变异数 \u002F 总变异数，目标 ≥ 80%。\n\n## Mock 边界（单元测试）\n\n### 单元测试中应该 Mock 的\n\n| 依赖                | 原因                                |\n| ------------------- | ----------------------------------- |\n| 数据库              | 单元测试不碰真实 DB（那是集成测试） |\n| 网络请求 \u002F 外部 API | 不可控、慢                          |\n| 文件系统            | 速度和隔离                          |\n| 时间                | 保证确定性                          |\n\n### 不应该 Mock 的\n\n| 依赖                         | 原因            |\n| ---------------------------- | --------------- |\n| 被测函数内部调用的同模块函数 | 要验证真实协作  |\n| 纯函数 \u002F 工具函数            | Mock 它们无意义 |\n| 数据结构 \u002F 常量              | 不是行为依赖    |\n\n**判断标准**：如果一个依赖的行为会被测试直接验证，就不要 Mock 它。\n\n## 测试反模式（禁止）\n\n| 反模式                       | 问题                 | 正确做法            |\n| ---------------------------- | -------------------- | ------------------- |\n| **一个测试多个断言无关行为** | 失败时不知道哪里坏了 | 拆分多个测试        |\n| **测试实现细节而非行为**     | 重构就全挂           | 测输入输出          |\n| **Mock 一切**                | 测的是 Mock 不是代码 | 只 Mock 外部依赖    |\n| **测试间共享状态**           | 顺序依赖、flaky      | beforeEach 重建     |\n| **try-catch 吞异常**         | 测试永远通过         | 让断言抛错          |\n| **用随机数据不固定种子**     | 不可重复             | 固定种子或用固定值  |\n| **只测 happy path**          | 边界没覆盖           | 必须有边界\u002F异常用例 |\n\n## 检查清单\n\n- [ ] 每个被测单元有对应测试文件\n- [ ] 测试遵循 AAA 模式\n- [ ] 测试命名表达行为意图\n- [ ] 覆盖 happy path + 边界值 + 异常情况\n- [ ] 只 Mock 外部依赖，不 Mock 被测逻辑\n- [ ] 测试间无共享状态，可独立运行\n- [ ] 测试快速执行（毫秒级）\n- [ ] 无 try-catch 吞异常\n- [ ] 无测试实现细节（只测行为）\n","# 单元测试方法论\n\n## 单元测试的定义与原则\n\n单元测试验证**最小可测试单元**（函数、方法、类、组件）的行为，隔离外部依赖。\n\n### 核心原则\n\n| 原则     | 说明                                             |\n| -------- | ------------------------------------------------ |\n| **隔离** | 一个测试只验证一个行为，不依赖其他测试或外部系统 |\n| **快速** | 毫秒级执行，全部单元测试应在秒级完成             |\n| **确定** | 相同输入多次运行结果一致，不依赖时间\u002F网络\u002F随机数 |\n| **可读** | 测试代码即文档，命名清晰表达意图                 |\n| **独立** | 测试顺序不影响结果，可任意顺序执行               |\n\n### 什么该做单元测试\n\n| 应该测                   | 不应该测                       |\n| ------------------------ | ------------------------------ |\n| 纯函数 \u002F 工具函数        | 框架内部行为（React 渲染机制） |\n| Service 层业务逻辑       | 第三方库本身                   |\n| 组件渲染与交互（前端）   | 配置文件 \u002F 常量                |\n| Hook 状态逻辑            | 简单的 getter\u002Fsetter           |\n| 校验 \u002F 转换 \u002F 格式化逻辑 | 数据库查询（属于集成测试）     |\n| 状态机 \u002F 状态转换        | 网络请求（属于集成测试）       |\n\n## AAA 模式（Arrange-Act-Assert）\n\n每个单元测试遵循三段式结构：\n\n```typescript\nit('applies 10% discount when total > 100', () => {\n  \u002F\u002F Arrange — 准备测试数据和环境\n  const items = [{ price: 60, quantity: 2 }]; \u002F\u002F total = 120\n  const discount = 0.1;\n\n  \u002F\u002F Act — 执行被测逻辑\n  const result = calculateTotal(items, discount);\n\n  \u002F\u002F Assert — 验证结果\n  expect(result).toBe(108); \u002F\u002F 120 * 0.9\n});\n```\n\n**命名规范**：`[期望行为] when [条件]` 或 `[动作] [结果]`\n\n```typescript\n\u002F\u002F ✅ 好\nit('returns error when email is invalid');\nit('calculates total with discount applied');\n\n\u002F\u002F ❌ 差\nit('should work');\nit('test1');\n```\n\n## Test Doubles（测试替身）\n\n根据用途选择不同的替身类型：\n\n| 类型      | 用途                 | 示例                                    |\n| --------- | -------------------- | --------------------------------------- |\n| **Dummy** | 占位，不被调用       | 传一个空对象满足参数签名                |\n| **Stub**  | 提供预设返回值       | `repo.findById.mockResolvedValue(user)` |\n| **Spy**   | 记录调用信息         | `expect(fn).toHaveBeenCalledWith(arg)`  |\n| **Mock**  | Stub + Spy，验证交互 | `mock.calledWith(...)`                  |\n| **Fake**  | 简化的真实实现       | 内存数据库替代真实 DB                   |\n\n### 何时使用哪种\n\n```typescript\n\u002F\u002F Stub：被测代码需要依赖返回值，但不关心调用细节\njest.mock('..\u002Frepo', () => ({\n  findById: jest.fn().mockResolvedValue({ id: '1', name: 'Alice' }),\n}));\n\n\u002F\u002F Spy：需要验证依赖是否被正确调用\nconst emailSpy = jest.spyOn(emailService, 'send');\nawait userService.register(user);\nexpect(emailSpy).toHaveBeenCalledWith(user.email, expect.any(String));\n\n\u002F\u002F Fake：需要一个可用但简化的实现\nclass FakeCache implements Cache {\n  private store = new Map\u003Cstring, string>();\n  async get(k: string) {\n    return this.store.get(k) ?? null;\n  }\n  async set(k: string, v: string) {\n    this.store.set(k, v);\n  }\n}\n```\n\n## 前端单元测试\n\n### 组件渲染测试\n\n```typescript\n\u002F\u002F Button.test.tsx\nimport { render, screen } from '@testing-library\u002Freact';\nimport userEvent from '@testing-library\u002Fuser-event';\nimport { Button } from '.\u002FButton';\n\ndescribe('Button', () => {\n  it('renders children text', () => {\n    render(\u003CButton>Click me\u003C\u002FButton>);\n    expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();\n  });\n\n  it('calls onClick when clicked', async () => {\n    const handleClick = jest.fn();\n    render(\u003CButton onClick={handleClick}>Click\u003C\u002FButton>);\n\n    await userEvent.click(screen.getByRole('button', { name: 'Click' }));\n\n    expect(handleClick).toHaveBeenCalledTimes(1);\n  });\n\n  it('does not call onClick when disabled', async () => {\n    const handleClick = jest.fn();\n    render(\u003CButton onClick={handleClick} disabled>Click\u003C\u002FButton>);\n\n    await userEvent.click(screen.getByRole('button', { name: 'Click' }));\n\n    expect(handleClick).not.toHaveBeenCalled();\n  });\n\n  it('applies variant styles', () => {\n    const { container } = render(\u003CButton variant=\"primary\">Save\u003C\u002FButton>);\n    expect(container.firstChild).toHaveClass('btn-primary');\n  });\n});\n```\n\n### Hook 测试\n\n```typescript\n\u002F\u002F useCounter.test.ts\nimport { renderHook, act } from '@testing-library\u002Freact';\nimport { useCounter } from '.\u002FuseCounter';\n\ndescribe('useCounter', () => {\n  it('initializes with default value 0', () => {\n    const { result } = renderHook(() => useCounter());\n    expect(result.current.count).toBe(0);\n  });\n\n  it('initializes with provided value', () => {\n    const { result } = renderHook(() => useCounter(10));\n    expect(result.current.count).toBe(10);\n  });\n\n  it('increments count', () => {\n    const { result } = renderHook(() => useCounter());\n    act(() => result.current.increment());\n    expect(result.current.count).toBe(1);\n  });\n\n  it('decrements count but not below 0', () => {\n    const { result } = renderHook(() => useCounter(0));\n    act(() => result.current.decrement());\n    expect(result.current.count).toBe(0); \u002F\u002F 边界：不低于 0\n  });\n\n  it('resets to initial value', () => {\n    const { result } = renderHook(() => useCounter(5));\n    act(() => result.current.increment());\n    act(() => result.current.reset());\n    expect(result.current.count).toBe(5);\n  });\n});\n```\n\n### 工具函数测试\n\n```typescript\n\u002F\u002F formatDate.test.ts\nimport { formatDate, formatCurrency, maskEmail } from '.\u002Fformat';\n\ndescribe('formatDate', () => {\n  it('formats ISO date to YYYY-MM-DD', () => {\n    expect(formatDate('2024-01-15T10:30:00Z')).toBe('2024-01-15');\n  });\n\n  it('handles invalid date gracefully', () => {\n    expect(formatDate('invalid')).toBe('');\n  });\n});\n\ndescribe('maskEmail', () => {\n  it('masks local part of email', () => {\n    expect(maskEmail('alice@example.com')).toBe('a***@example.com');\n  });\n\n  it('handles short local part', () => {\n    expect(maskEmail('ab@example.com')).toBe('a*@example.com');\n  });\n\n  it('returns empty for invalid email', () => {\n    expect(maskEmail('not-an-email')).toBe('');\n  });\n});\n```\n\n## 后端单元测试\n\n### Service 层测试（Mock Repository）\n\n```typescript\n\u002F\u002F userService.test.ts\nimport { UserService } from '.\u002FuserService';\n\n\u002F\u002F Mock 整个 Repository 模块\nconst mockFindById = jest.fn();\nconst mockCreate = jest.fn();\njest.mock('..\u002Frepositories\u002FuserRepository', () => ({\n  UserRepository: jest.fn().mockImplementation(() => ({\n    findById: mockFindById,\n    create: mockCreate,\n  })),\n}));\n\ndescribe('UserService', () => {\n  let service: UserService;\n\n  beforeEach(() => {\n    jest.clearAllMocks();\n    service = new UserService();\n  });\n\n  describe('getById', () => {\n    it('returns user when found', async () => {\n      const user = { id: '1', name: 'Alice', email: 'alice@example.com' };\n      mockFindById.mockResolvedValue(user);\n\n      const result = await service.getById('1');\n\n      expect(result).toEqual(user);\n      expect(mockFindById).toHaveBeenCalledWith('1');\n    });\n\n    it('throws NotFoundError when user does not exist', async () => {\n      mockFindById.mockResolvedValue(null);\n\n      await expect(service.getById('999')).rejects.toThrow('User not found');\n    });\n  });\n\n  describe('create', () => {\n    it('creates user when email is unique', async () => {\n      const data = { name: 'Bob', email: 'bob@example.com' };\n      mockFindById.mockResolvedValue(null); \u002F\u002F 邮箱不存在\n      mockCreate.mockResolvedValue({ id: '2', ...data });\n\n      const result = await service.create(data);\n\n      expect(result).toEqual({ id: '2', ...data });\n      expect(mockCreate).toHaveBeenCalledWith(data);\n    });\n\n    it('throws ConflictError when email exists', async () => {\n      mockFindById.mockResolvedValue({ id: '1', email: 'exists@example.com' });\n\n      await expect(service.create({ name: 'X', email: 'exists@example.com' })).rejects.toThrow(\n        'Email already exists',\n      );\n\n      expect(mockCreate).not.toHaveBeenCalled(); \u002F\u002F 不应调用创建\n    });\n  });\n});\n```\n\n### 纯业务逻辑测试\n\n```typescript\n\u002F\u002F pricing.test.ts\nimport { calculatePrice, applyCoupon } from '.\u002Fpricing';\n\ndescribe('calculatePrice', () => {\n  it('sums item prices', () => {\n    const items = [\n      { price: 100, quantity: 2 },\n      { price: 50, quantity: 1 },\n    ];\n    expect(calculatePrice(items)).toBe(250);\n  });\n\n  it('returns 0 for empty items', () => {\n    expect(calculatePrice([])).toBe(0);\n  });\n\n  it('throws on negative quantity', () => {\n    expect(() => calculatePrice([{ price: 10, quantity: -1 }])).toThrow(\n      'Quantity must be positive',\n    );\n  });\n});\n\ndescribe('applyCoupon', () => {\n  const basePrice = 100;\n\n  it('applies percentage discount', () => {\n    expect(applyCoupon(basePrice, { type: 'percent', value: 20 })).toBe(80);\n  });\n\n  it('applies fixed amount discount', () => {\n    expect(applyCoupon(basePrice, { type: 'fixed', value: 30 })).toBe(70);\n  });\n\n  it('does not go below 0', () => {\n    expect(applyCoupon(10, { type: 'fixed', value: 100 })).toBe(0);\n  });\n\n  it('caps percentage at 100', () => {\n    expect(applyCoupon(basePrice, { type: 'percent', value: 150 })).toBe(0);\n  });\n});\n```\n\n## Python 单元测试\n\n```python\n# tests\u002Funit\u002Ftest_pricing.py\nimport pytest\nfrom app.pricing import calculate_price, apply_coupon\n\nclass TestCalculatePrice:\n    def test_sums_item_prices(self):\n        items = [{\"price\": 100, \"quantity\": 2}, {\"price\": 50, \"quantity\": 1}]\n        assert calculate_price(items) == 250\n\n    def test_empty_items_returns_zero(self):\n        assert calculate_price([]) == 0\n\n    def test_negative_quantity_raises(self):\n        with pytest.raises(ValueError, match=\"Quantity must be positive\"):\n            calculate_price([{\"price\": 10, \"quantity\": -1}])\n\n\nclass TestApplyCoupon:\n    @pytest.mark.parametrize(\"coupon_type,value,expected\", [\n        (\"percent\", 20, 80),\n        (\"fixed\", 30, 70),\n        (\"percent\", 100, 0),\n        (\"percent\", 150, 0),  # cap at 0\n    ])\n    def test_applies_discount(self, coupon_type, value, expected):\n        coupon = {\"type\": coupon_type, \"value\": value}\n        assert apply_coupon(100, coupon) == expected\n\n    def test_does_not_go_below_zero(self):\n        assert apply_coupon(10, {\"type\": \"fixed\", \"value\": 100}) == 0\n```\n\n### Python Mock 示例\n\n```python\n# tests\u002Funit\u002Ftest_user_service.py\nfrom unittest.mock import Mock, patch\nfrom app.services.user_service import UserService\n\nclass TestUserService:\n    def test_get_by_id_returns_user(self):\n        mock_repo = Mock()\n        mock_repo.find_by_id.return_value = {\"id\": \"1\", \"name\": \"Alice\"}\n        service = UserService(mock_repo)\n\n        result = service.get_by_id(\"1\")\n\n        assert result[\"name\"] == \"Alice\"\n        mock_repo.find_by_id.assert_called_once_with(\"1\")\n\n    def test_get_by_id_raises_when_not_found(self):\n        mock_repo = Mock()\n        mock_repo.find_by_id.return_value = None\n        service = UserService(mock_repo)\n\n        with pytest.raises(ValueError, match=\"User not found\"):\n            service.get_by_id(\"999\")\n```\n\n## Go 单元测试\n\n```go\n\u002F\u002F pricing_test.go\npackage pricing\n\nimport \"testing\"\n\nfunc TestCalculatePrice(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\titems []Item\n\t\twant  int\n\t}{\n\t\t{\"sums prices\", []Item{{Price: 100, Qty: 2}, {Price: 50, Qty: 1}}, 250},\n\t\t{\"empty items\", []Item{}, 0},\n\t\t{\"single item\", []Item{{Price: 10, Qty: 3}}, 30},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := CalculatePrice(tt.items)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"CalculatePrice() = %d, want %d\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCalculatePriceNegativeQty(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"expected panic for negative quantity\")\n\t\t}\n\t}()\n\tCalculatePrice([]Item{{Price: 10, Qty: -1}})\n}\n```\n\n### Go 接口 Mock\n\n```go\n\u002F\u002F user_service_test.go\npackage service\n\nimport (\n\t\"testing\"\n\t\"github.com\u002Fstretchr\u002Ftestify\u002Fassert\"\n\t\"github.com\u002Fstretchr\u002Ftestify\u002Fmock\"\n)\n\n\u002F\u002F Mock Repository\ntype MockUserRepo struct {\n\tmock.Mock\n}\n\nfunc (m *MockUserRepo) FindByID(id string) (*User, error) {\n\targs := m.Called(id)\n\tif args.Get(0) == nil {\n\t\treturn nil, args.Error(1)\n\t}\n\treturn args.Get(0).(*User), args.Error(1)\n}\n\nfunc TestUserService_GetByID(t *testing.T) {\n\tmockRepo := new(MockUserRepo)\n\tmockRepo.On(\"FindByID\", \"1\").Return(&User{ID: \"1\", Name: \"Alice\"}, nil)\n\n\tservice := NewUserService(mockRepo)\n\tuser, err := service.GetByID(\"1\")\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"Alice\", user.Name)\n\tmockRepo.AssertExpectations(t)\n}\n```\n\n## Java 单元测试\n\n```java\n\u002F\u002F PricingTest.java\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.CsvSource;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass PricingTest {\n\n    @Test\n    void sumsItemPrices() {\n        var items = List.of(\n            new Item(100, 2),\n            new Item(50, 1)\n        );\n        assertEquals(250, Pricing.calculatePrice(items));\n    }\n\n    @ParameterizedTest\n    @CsvSource({\n        \"percent, 20, 80\",\n        \"fixed, 30, 70\",\n        \"percent, 100, 0\",\n    })\n    void appliesDiscount(String type, int value, int expected) {\n        var coupon = new Coupon(type, value);\n        assertEquals(expected, Pricing.applyCoupon(100, coupon));\n    }\n\n    @Test\n    void throwsOnNegativeQuantity() {\n        var items = List.of(new Item(10, -1));\n        assertThrows(IllegalArgumentException.class,\n            () -> Pricing.calculatePrice(items));\n    }\n}\n```\n\n### Java Mockito 示例\n\n```java\n\u002F\u002F UserServiceTest.java\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.junit.jupiter.MockitoExtension;\nimport static org.mockito.Mockito.*;\nimport static org.junit.jupiter.api.Assertions.*;\n\n@ExtendWith(MockitoExtension.class)\nclass UserServiceTest {\n\n    @Mock\n    private UserRepository userRepository;\n\n    @InjectMocks\n    private UserService userService;\n\n    @Test\n    void getByIdReturnsUser() {\n        var user = new User(\"1\", \"Alice\");\n        when(userRepository.findById(\"1\")).thenReturn(Optional.of(user));\n\n        var result = userService.getById(\"1\");\n\n        assertEquals(\"Alice\", result.getName());\n        verify(userRepository).findById(\"1\");\n    }\n\n    @Test\n    void getByIdThrowsWhenNotFound() {\n        when(userRepository.findById(\"999\")).thenReturn(Optional.empty());\n\n        assertThrows(UserNotFoundException.class,\n            () -> userService.getById(\"999\"));\n    }\n}\n```\n\n## 边界值与特殊情况\n\n单元测试必须覆盖边界：\n\n| 边界类型          | 示例                              |\n| ----------------- | --------------------------------- |\n| **空值**          | 空字符串、空数组、null、undefined |\n| **零值**          | 数量为 0、金额为 0                |\n| **最小值\u002F最大值** | 字符串最大长度、数值上下限        |\n| **负数**          | 负数数量、负数金额                |\n| **类型边界**      | 整数溢出、浮点数精度              |\n| **日期时间**      | 闰年、时区、夏令时、跨年          |\n| **集合边界**      | 单元素、刚好达到上限、超过上限    |\n\n```typescript\ndescribe('pagination', () => {\n  it('returns first page when page is 1', () => {\n    expect(paginate(items, 1, 10)).toEqual(items.slice(0, 10));\n  });\n\n  it('returns empty array when page exceeds total', () => {\n    expect(paginate([1, 2, 3], 10, 10)).toEqual([]);\n  });\n\n  it('clamps pageSize to max', () => {\n    expect(paginate(items, 1, 1000).length).toBeLessThanOrEqual(100);\n  });\n\n  it('handles page 0 as page 1', () => {\n    expect(paginate(items, 0, 10)).toEqual(paginate(items, 1, 10));\n  });\n});\n```\n\n## 错误与异常测试\n\n```typescript\ndescribe('error handling', () => {\n  it('throws custom error with code', () => {\n    expect(() => validateEmail('invalid')).toThrow(\n      expect.objectContaining({ code: 'INVALID_EMAIL' }),\n    );\n  });\n\n  it('rejects promise with typed error', async () => {\n    await expect(service.delete('not-owner-id')).rejects.toMatchObject({\n      code: 'FORBIDDEN',\n      status: 403,\n    });\n  });\n\n  it('does not throw for valid input', () => {\n    expect(() => validateEmail('a@b.com')).not.toThrow();\n  });\n});\n```\n\n## 属性测试（Property-Based Testing）\n\n对纯函数，用随机生成的输入验证不变量：\n\n```typescript\n\u002F\u002F 使用 fast-check\nimport fc from 'fast-check';\n\ndescribe('reverse function (property test)', () => {\n  it('reverse of reverse equals original', () => {\n    fc.assert(\n      fc.property(fc.array(fc.integer()), (arr) => {\n        expect(reverse(reverse(arr))).toEqual(arr);\n      }),\n    );\n  });\n\n  it('reverse preserves length', () => {\n    fc.assert(\n      fc.property(fc.array(fc.integer()), (arr) => {\n        expect(reverse(arr)).toHaveLength(arr.length);\n      }),\n    );\n  });\n});\n```\n\n## 变异测试（Mutation Testing）\n\n变异测试验证测试的有效性：故意修改源代码（变异），检查测试是否能捕获。\n\n```bash\n# Node.js (Stryker)\nnpx stryker run\n\n# Python (mutmut)\nmutmut run\n\n# Go\ngo test -run TestMutate -v\n```\n\n**变异算子**：\n- `a + b` → `a - b`\n- `a > b` → `a >= b`\n- `&&` → `||`\n- `return x` → `return 0` \u002F `return null`\n\n**变异得分** = 被杀变异数 \u002F 总变异数，目标 ≥ 80%。\n\n## Mock 边界（单元测试）\n\n### 单元测试中应该 Mock 的\n\n| 依赖                | 原因                                |\n| ------------------- | ----------------------------------- |\n| 数据库              | 单元测试不碰真实 DB（那是集成测试） |\n| 网络请求 \u002F 外部 API | 不可控、慢                          |\n| 文件系统            | 速度和隔离                          |\n| 时间                | 保证确定性                          |\n\n### 不应该 Mock 的\n\n| 依赖                         | 原因            |\n| ---------------------------- | --------------- |\n| 被测函数内部调用的同模块函数 | 要验证真实协作  |\n| 纯函数 \u002F 工具函数            | Mock 它们无意义 |\n| 数据结构 \u002F 常量              | 不是行为依赖    |\n\n**判断标准**：如果一个依赖的行为会被测试直接验证，就不要 Mock 它。\n\n## 测试反模式（禁止）\n\n| 反模式                       | 问题                 | 正确做法            |\n| ---------------------------- | -------------------- | ------------------- |\n| **一个测试多个断言无关行为** | 失败时不知道哪里坏了 | 拆分多个测试        |\n| **测试实现细节而非行为**     | 重构就全挂           | 测输入输出          |\n| **Mock 一切**                | 测的是 Mock 不是代码 | 只 Mock 外部依赖    |\n| **测试间共享状态**           | 顺序依赖、flaky      | beforeEach 重建     |\n| **try-catch 吞异常**         | 测试永远通过         | 让断言抛错          |\n| **用随机数据不固定种子**     | 不可重复             | 固定种子或用固定值  |\n| **只测 happy path**          | 边界没覆盖           | 必须有边界\u002F异常用例 |\n\n## 检查清单\n\n- [ ] 每个被测单元有对应测试文件\n- [ ] 测试遵循 AAA 模式\n- [ ] 测试命名表达行为意图\n- [ ] 覆盖 happy path + 边界值 + 异常情况\n- [ ] 只 Mock 外部依赖，不 Mock 被测逻辑\n- [ ] 测试间无共享状态，可独立运行\n- [ ] 测试快速执行（毫秒级）\n- [ ] 无 try-catch 吞异常\n- [ ] 无测试实现细节（只测行为）\n",{},"main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Funit-testing",491,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-14 14:06:13",{"source":7,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill unit-testing",{"tool":42,"command":43},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill unit-testing",{"tool":45,"command":46},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill unit-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Funit-testing\u002FSKILL.md",true,[],[51,61,69,77,85,93],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":56,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":60},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":65,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":60},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":60},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":81,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":60},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":60},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":97,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":60},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]