08ea5fbe98
添加用户管理视图、API和状态管理文件
2.6 KiB
2.6 KiB
测试最佳实践
测试设计原则
1. 测试金字塔
- 70% 单元测试
- 20% 集成测试
- 10% E2E测试
2. 测试独立性
每个测试用例应该独立运行,不依赖其他测试。
3. 测试可重复性
测试结果应该稳定可重复,不受环境影响。
4. 测试快速反馈
优先测试核心业务流程,提供快速反馈。
编写测试的最佳实践
1. 使用描述性的测试名称
test('TC-USER-001: 用户登录成功', async ({ page }) => {
// 测试代码
});
2. 使用测试夹具
test('示例测试', async ({
page,
testConfig,
testLogger,
testDataManager
}) => {
testLogger.startTest('示例测试');
// 测试代码
testLogger.endTest('示例测试', 'passed');
});
3. 记录测试步骤
testLogger.startStep('步骤1: 打开登录页面');
await page.goto('/login');
testLogger.endStep('步骤1: 打开登录页面', 'passed');
4. 使用辅助工具
const formHelper = new FormHelper(page);
await formHelper.fillField('input[name="username"]', 'testuser');
await formHelper.submitForm();
5. 清理测试数据
test.afterEach(async ({ testDataManager }) => {
await testDataManager.cleanup();
});
常见陷阱
1. 硬编码等待时间
❌ 不推荐:
await page.waitForTimeout(5000);
✅ 推荐:
await page.waitForSelector('.element', { state: 'visible' });
2. 测试数据冲突
❌ 不推荐:
const username = 'testuser'; // 固定用户名
✅ 推荐:
const username = `testuser_${Date.now()}`; // 唯一用户名
3. 测试用例依赖
❌ 不推荐:
test('测试1', async () => {
// 创建数据
});
test('测试2', async () => {
// 依赖测试1的数据
});
✅ 推荐:
test('测试1', async ({ testDataManager }) => {
const data = await testDataManager.createTestData();
// 使用数据
});
test('测试2', async ({ testDataManager }) => {
const data = await testDataManager.createTestData();
// 使用独立数据
});
性能优化
1. 并行执行
// playwright.config.ts
export default defineConfig({
workers: 4, // 并行执行
});
2. 跳过慢速测试
test.skip('慢速测试', async () => {
// 测试代码
});
3. 使用项目分组
// playwright.config.ts
export default defineConfig({
projects: [
{ name: 'fast', testMatch: '**/*.fast.spec.ts' },
{ name: 'slow', testMatch: '**/*.slow.spec.ts' }
]
});