Claude cho Engineering: Chiến lược testing toàn diện
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Muốn làm chủ testing pyramid: nền tảng của testing strategy, hãy bắt đầu từ việc hiểu Testing Pyramid là framework cổ điển nhưng vẫn đúng: / E2E Tests / ít, chậm, đắt / Integration Tests / vừa phải, tốc độ TB / Unit Tests / nhiều, nhanh, rẻ nhất Unit Tests 70%: Test từng function/ lập — kỹ thuật này được nhiều developer áp dụng thành công trong dự án thực tế.
- 2 Một thực tế quan trọng về điều gì nên và không nên test: Nên test: Business-critical paths checkout, authentication, payment Error handling và edge cases Security boundaries Data integrity Regression từ các bugs đã fix Bỏ qua: Trivial getters/setters Framework code test framework, không test code của bạn One-off scripts Generated code — tuy mang lại lợi ích rõ ràng nhưng cũng đòi hỏi đầu tư thời gian học và thử nghiệm phù hợp.
- 3 Dữ liệu từ ví dụ test plan từ claude cho thấy: ## Testing Strategy: Payment Service ### Mục tiêu coverage - Unit tests: 70% coverage focus business logic - Integration tests: Key API flows - E2E: 3 critical user journeys ### Unit Tests Jest **Payment Intent Service:** — những con số này phản ánh mức độ cải thiện thực tế mà người dùng có thể kỳ vọng.
- 4 Bước thực hành then chốt trong prompt mẫu: identify gaps trong coverage hiện tại: Đây là coverage report từ Jest jest --coverage: File | % Stmts | % Branch | % Funcs | ------------------------|---------|----------|---------| orderService.js | 45.2 | 30.1 | 50.0 | paymentService.js | 82.3 | 71.4 | 88.9 | userService.js | 23 — nắm vững điều này giúp bạn triển khai nhanh hơn và giảm thiểu lỗi thường gặp.
- 5 Một thực tế quan trọng về xây dựng test culture trong team: Team của tôi 6 engineers, không có test culture. Coverage hiện tại: 12%. Tôi muốn build test culture trong 3 tháng mà không gây friction hoặc làm team frustrated. Hãy đề xuất: 1. Starting point đừng overwhelm team 2 — tuy mang lại lợi ích rõ ràng nhưng cũng đòi hỏi đầu tư thời gian học và thử nghiệm phù hợp.
Testing không phải là thứ thêm vào sau khi viết xong code — nó là một phần của engineering process. Nhưng nhiều team không biết nên test gì, test bao nhiêu, và dùng loại test nào cho mỗi component. Claude có thể giúp bạn thiết kế testing strategy phù hợp với codebase, viết test cases cụ thể, và xác định các gap trong coverage hiện tại.
Testing Pyramid: Nền tảng của testing strategy
Testing Pyramid là framework cổ điển nhưng vẫn đúng:
/ E2E Tests / (ít, chậm, đắt) / Integration Tests / (vừa phải, tốc độ TB) / Unit Tests / (nhiều, nhanh, rẻ nhất)
- Unit Tests (70%): Test từng function/class độc lập, mock dependencies. Nhanh, rẻ, nhiều.
- Integration Tests (20%): Test nhiều components làm việc cùng nhau, ví dụ API + Database.
- E2E Tests (10%): Test toàn bộ user flow qua browser/API. Chậm nhưng confidence cao nhất.
Testing strategy theo loại component
| Component | Test approach |
|---|---|
| API endpoints | Unit tests cho business logic, integration tests cho HTTP layer, contract tests cho consumers |
| Data pipelines | Input validation, transformation correctness, idempotency tests |
| Frontend | Component tests, interaction tests, visual regression, accessibility |
| Infrastructure | Smoke tests, chaos engineering, load tests |
Điều gì nên và không nên test
Nên test:
- Business-critical paths (checkout, authentication, payment)
- Error handling và edge cases
- Security boundaries
- Data integrity
- Regression từ các bugs đã fix
Bỏ qua:
- Trivial getters/setters
- Framework code (test framework, không test code của bạn)
- One-off scripts
- Generated code
Prompt mẫu: Tạo testing strategy cho service mới
Hãy giúp tôi tạo testing strategy cho payment service mới:
Service: Node.js REST API xử lý payments
Integrations: Stripe, MoMo, database PostgreSQL, Redis cache
Critical paths:
- Create payment intent
- Confirm payment
- Refund
- Webhook processing từ Stripe/MoMo
Constraints:
- Team chưa có test culture (coverage hiện tại: 15%)
- 2 tháng để launch MVP
- Jest + Supertest đã được setup
Hãy tạo:
1. Test plan đầy đủ theo Testing Pyramid
2. Coverage targets cho từng layer
3. Ví dụ test cases cho 2-3 scenarios quan trọng nhất
4. Approach để build test culture dần dần
Ví dụ test plan từ Claude
## Testing Strategy: Payment Service
### Mục tiêu coverage
- Unit tests: 70% coverage (focus business logic)
- Integration tests: Key API flows
- E2E: 3 critical user journeys
### Unit Tests (Jest)
**Payment Intent Service:**
- Create intent với valid data -> return intent object
- Create intent với amount = 0 -> ValidationError
- Create intent với currency không hỗ trợ -> ValidationError
- Retry logic khi Stripe timeout (mock Stripe SDK)
- Idempotency: 2 requests cùng idempotency_key -> same result
**Refund Service:**
- Full refund happy path
- Partial refund (amount < original)
- Refund amount > original payment -> Error
- Refund đã cancelled order -> Error
### Integration Tests (Supertest + Test DB)
**POST /api/payments:**
- 201 với valid body
- 400 với missing fields
- 422 với invalid card (Stripe test token)
- 401 với missing/invalid JWT
- 429 khi exceed rate limit
**Webhook processing:**
- payment_intent.succeeded -> update order status
- payment_intent.payment_failed -> notify user
- Stripe signature validation fail -> 400
- Duplicate event (idempotency) -> 200 nhưng không process lại
### E2E Tests (Playwright)
**Happy path checkout:**
1. Add to cart -> checkout -> payment -> confirmation
2. Verify order status updated
3. Verify email sent (mock email service)
### Coverage Targets
- Sprint 1: 30% (unit tests cho payment intent + refund)
- Sprint 2: 50% (thêm webhook + API tests)
- Sprint 3: 70% (fill gaps, add E2E)
- Sau launch: Maintain 70%, thêm regression tests
Prompt mẫu: Viết tests cụ thể
Viết Jest unit tests cho function này:
async function calculateOrderTotal(items, userId) {
const user = await UserService.getById(userId);
const discount = user.isPremium ? 0.1 : 0;
const subtotal = items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);
const tax = subtotal * 0.1; // VAT 10%
const discountAmount = subtotal * discount;
return {
subtotal,
tax,
discount: discountAmount,
total: subtotal + tax - discountAmount
};
}
Hãy viết tests bao gồm:
1. Happy path (user thường và premium)
2. Edge cases (empty items, zero quantity, large amounts)
3. Error cases (user không tồn tại)
4. Dùng Jest mocks cho UserService
Ví dụ test code từ Claude
const { calculateOrderTotal } = require('./orderService');
const UserService = require('./userService');
jest.mock('./userService');
describe('calculateOrderTotal', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('regular user', () => {
beforeEach(() => {
UserService.getById.mockResolvedValue({ isPremium: false });
});
it('calculates total correctly', async () => {
const items = [
{ price: 100000, quantity: 2 },
{ price: 50000, quantity: 1 }
];
const result = await calculateOrderTotal(items, 'user-123');
expect(result.subtotal).toBe(250000);
expect(result.tax).toBe(25000);
expect(result.discount).toBe(0);
expect(result.total).toBe(275000);
});
});
describe('premium user', () => {
beforeEach(() => {
UserService.getById.mockResolvedValue({ isPremium: true });
});
it('applies 10% discount', async () => {
const items = [{ price: 100000, quantity: 1 }];
const result = await calculateOrderTotal(items, 'user-456');
expect(result.discount).toBe(10000);
expect(result.total).toBe(100000);
});
});
describe('edge cases', () => {
it('returns zeros for empty items', async () => {
UserService.getById.mockResolvedValue({ isPremium: false });
const result = await calculateOrderTotal([], 'user-123');
expect(result.subtotal).toBe(0);
expect(result.total).toBe(0);
});
it('handles large amounts without floating point errors', async () => {
UserService.getById.mockResolvedValue({ isPremium: false });
const items = [{ price: 999999999, quantity: 100 }];
const result = await calculateOrderTotal(items, 'user-123');
expect(Number.isFinite(result.total)).toBe(true);
});
});
describe('error cases', () => {
it('throws when user not found', async () => {
UserService.getById.mockRejectedValue(new Error('User not found'));
await expect(
calculateOrderTotal([{ price: 100, quantity: 1 }], 'invalid-id')
).rejects.toThrow('User not found');
});
});
});
Prompt mẫu: Identify gaps trong coverage hiện tại
Đây là coverage report từ Jest (jest --coverage):
File | % Stmts | % Branch | % Funcs |
------------------------|---------|----------|---------|
orderService.js | 45.2 | 30.1 | 50.0 |
paymentService.js | 82.3 | 71.4 | 88.9 |
userService.js | 23.1 | 15.0 | 25.0 |
notificationService.js | 12.0 | 8.0 | 10.0 |
Business critical flows:
- Order creation và payment
- User registration và login
- Notification gửi khi đơn hàng thay đổi status
Hãy:
1. Identify các file cần test ngay (business critical + low coverage)
2. Suggest loại tests nào còn thiếu cho từng file
3. Estimate effort để đạt 70% coverage overall
4. Prioritize theo risk vs effort
Testing cho Vietnamese context
Viết test cases cho Vietnamese-specific logic:
1. Phone number validation (Viettel/Vinaphone/Mobifone)
2. Vietnamese ID card number validation (12 số)
3. Address parsing (Quận/Huyện, Phường/Xã)
4. Date formatting (DD/MM/YYYY vs ISO)
5. Currency formatting (1.000.000 đ)
Bao gồm cả test cases cho edge cases
đặc thù như số điện thoại 10 vs 11 số cũ.
Xây dựng test culture trong team
Team của tôi 6 engineers, không có test culture.
Coverage hiện tại: 12%.
Tôi muốn build test culture trong 3 tháng
mà không gây friction hoặc làm team frustrated.
Hãy đề xuất:
1. Starting point (đừng overwhelm team)
2. Quick wins để show value của testing
3. Làm thế nào để integrate vào PR process
4. Metrics để track progress
5. Cách handle pushback "testing làm chậm development"
Mẹo testing hiệu quả
- Test behavior, không phải implementation: Test rằng function trả về đúng kết quả, không phải nó gọi method nào internally.
- Một assertion rõ ràng mỗi test: Khi test fail, bạn biết chính xác điều gì bị vỡ.
- Test tên mô tả behavior: "should apply 10% discount for premium users" tốt hơn "test discount".
- Bắt đầu với critical paths: Đừng cố 100% coverage ngay. Test checkout, auth, payment trước.
- Regression tests sau bug: Mỗi bug fix phải đi kèm test ngăn nó tái diễn.
Bước tiếp theo
Testing tốt là investment, không phải overhead:
- Thư viện ứng dụng Claude cho Engineering
- Kết hợp với Code Review workflow để enforce test coverage trong PR process
- Dùng Tech Debt workflow để plan systematic improvement của test coverage
Bài viết liên quan
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.




