📚 Bổ trợ Tutorial là phần thực hành bổ trợ cho bài học chính.
← Quay lại Tutorial Hub
💻 Dev intermediate v1.0 Cập nhật: 2026-03-06

Agent sinh test cases từ code

Sử dụng AI Agent để tự động generate unit tests, integration tests, và edge case scenarios từ source code.

1

Vấn đề

Writing tests thủ công tốn thời gian và dev thường chỉ test happy path. Edge cases, boundary conditions, và error scenarios bị bỏ qua. Test coverage thấp dẫn đến bugs lọt vào production.

2

Kết quả mong đợi

Bộ test cases bao gồm: unit tests cho mỗi function/method, integration tests cho API endpoints, edge case scenarios, và error handling tests. Coverage target: > 80%.

3

Yêu cầu trước khi bắt đầu

  • Source code cần test
  • Testing framework đã setup (Jest, Vitest, pytest, etc.)
  • AI tool hỗ trợ code generation
4

Prompt Pack

System Prompt

You are a QA Engineer who writes comprehensive test suites. You always cover: happy path, edge cases, boundary values, error scenarios, and integration points. You follow testing best practices: AAA pattern, descriptive names, no test interdependency.

Task Prompt

Write comprehensive tests for this code:

```
[PASTE CODE HERE]
```

Requirements:
1. Framework: [Jest/Vitest/pytest]
2. Cover: happy path, edge cases, error handling
3. Use AAA pattern (Arrange-Act-Assert)
4. Descriptive test names: 'should [expected behavior] when [condition]'
5. Mock external dependencies
6. Include at least 3 edge case scenarios

Guardrails

- Do NOT test implementation details, test behavior
- Do NOT create tests that depend on each other
- Every test must be independently runnable
- Include setup/teardown if needed
- Flag untestable code as 'NEEDS REFACTOR'
✓ Đã copy!
5

Workflow từng bước

1

Select code to test

Chọn module/function cần test. Ưu tiên business logic phức tạp.

2

Paste code + context

Paste code cùng với type definitions và external dependencies.

3

Review generated tests

Đọc tests, check logic assertions, verify edge cases reasonable.

4

Run & fix

Chạy tests, fix failures, thêm missing edge cases.

5

Check coverage

Run coverage report, thêm tests cho uncovered branches.

6

Demo Input / Output

📥 Input

```js function calculateDiscount(price, userType, couponCode) { if (price <= 0) throw new Error('Invalid price'); let discount = 0; if (userType === 'vip') discount = 0.2; if (couponCode === 'SAVE10') discount += 0.1; return price * (1 - Math.min(discount, 0.3)); } ```

📤 Output

```js
describe('calculateDiscount', () => {
  it('should apply 20% for VIP with no coupon', () => {
    expect(calculateDiscount(100, 'vip', '')).toBe(80);
  });
  it('should cap total discount at 30%', () => {
    expect(calculateDiscount(100, 'vip', 'SAVE10')).toBe(70);
  });
  it('should throw for zero price', () => {
    expect(() => calculateDiscount(0, 'regular', '')).toThrow('Invalid price');
  });
  // ... more edge cases
});
```
7

Failure Cases & Cách Fix

⚠️ Tests pass nhưng không meaningful
💡 Review assertions: mỗi test phải assert behavior, không chỉ 'no error'.
⚠️ Generated tests phụ thuộc internal implementation
💡 Thêm guardrail: 'Test public API only, not private methods.'
⚠️ Mock quá nhiều, test không reliable
💡 Dùng integration tests cho database / API layers thay vì mock everything.
8

Production Checklist

  • Tất cả tests pass
  • Coverage > 80%
  • Edge cases documented
  • Mocks realistic (không quá simplified)
  • Tests chạy < 30 giây
  • No flaky tests
✓ Đã copy!
9

Metrics theo dõi hiệu quả

Metric Target Cách đo
Code coverage > 80% Coverage report từ testing framework
Bug escape rate ≤ 1 bug/sprint lọt qua Track bugs found in production post-deploy
Test generation time < 30 phút / module Timestamp từ paste code → tests pass
10

Supporting Skill: Wireframe

👀 Hỗ trợ
### Wireframe cho Dev (mức hỗ trợ)

Khi viết tests cho UI components, wireframe giúp xác định visual states cần test:

1. **Identify UI states**: Từ wireframe, list states mỗi component: default, hover, active, disabled, loading, error
2. **Snapshot tests**: Tạo snapshot test cho mỗi state quan trọng

> Prompt: 'Based on this component wireframe, list all visual states that need snapshot tests.'