1. 首页 > IT综合教程 > 正文

IT教程FG408-自动化测试

内容大纲

1. 自动化测试概述

自动化测试是指使用软件工具自动执行测试用例,比较实际结果与预期结果,从而评估软件质量的过程。自动化测试可以提高测试效率,减少人为错误,加快软件发布周期。

自动化测试的核心优势包括:

  • 提高测试效率
  • 减少人为错误
  • 加快反馈周期
  • 支持持续集成
  • 提高测试覆盖率

学习交流加群风哥微信: itpux-com

2. 单元测试

2.1 JUnit单元测试

// JUnit单元测试示例
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {
private Calculator calculator;

@BeforeEach
public void setUp() {
calculator = new Calculator();
}

@AfterEach
public void tearDown() {
calculator = null;
}

@Test
public void testAdd() {
int result = calculator.add(2, 3);
assertEquals(5, result, “2 + 3 should equal 5”);
}

@Test
public void testSubtract() {
int result = calculator.subtract(5, 3);
assertEquals(2, result, “5 – 3 should equal 2”);
}

@Test
public void testMultiply() {
int result = calculator.multiply(2, 3);
assertEquals(6, result, “2 * 3 should equal 6”);
}

@Test
public void testDivide() {
double result = calculator.divide(6, 2);
assertEquals(3.0, result, 0.001, “6 / 2 should equal 3.0”);
}

@Test
public void testDivideByZero() {
assertThrows(ArithmeticException.class, () -> {
calculator.divide(1, 0);
}, “Division by zero should throw ArithmeticException”);
}
}

// 运行测试
$ mvn test

// 输出结果
[INFO] ——————————————————-
[INFO] T E S T S
[INFO] ——————————————————-
[INFO] Running com.fgedu.CalculatorTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————

2.2 Python单元测试

# Python单元测试示例
import unittest

class Calculator:
def add(self, a, b):
return a + b

def subtract(self, a, b):
return a – b

def multiply(self, a, b):
return a * b

def divide(self, a, b):
if b == 0:
raise ValueError(“Cannot divide by zero”)
return a / b

class CalculatorTest(unittest.TestCase):
def setUp(self):
self.calculator = Calculator()

def tearDown(self):
self.calculator = None

def test_add(self):
result = self.calculator.add(2, 3)
self.assertEqual(result, 5, “2 + 3 should equal 5”)

def test_subtract(self):
result = self.calculator.subtract(5, 3)
self.assertEqual(result, 2, “5 – 3 should equal 2”)

def test_multiply(self):
result = self.calculator.multiply(2, 3)
self.assertEqual(result, 6, “2 * 3 should equal 6”)

def test_divide(self):
result = self.calculator.divide(6, 2)
self.assertEqual(result, 3.0, “6 / 2 should equal 3.0”)

def test_divide_by_zero(self):
with self.assertRaises(ValueError):
self.calculator.divide(1, 0)

if __name__ == ‘__main__’:
unittest.main()

# 运行测试
$ python -m unittest calculator_test.py

# 输出结果
…..
———————————————————————-
Ran 5 tests in 0.001s

OK

2.3 单元测试最佳实践

  • 每个测试用例只测试一个功能点
  • 使用有意义的测试方法名
  • 保持测试的独立性
  • 覆盖边界条件和异常情况
  • 定期重构测试代码

风哥风哥提示:单元测试是自动化测试的基础,需要确保每个单元测试的独立性和可靠性。

3. 集成测试

3.1 Spring Boot集成测试

// Spring Boot集成测试示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(“test”)
public class UserControllerIntegrationTest {

@Autowired
private TestRestTemplate restTemplate;

@Autowired
private UserRepository userRepository;

@Test
public void testCreateUser() {
User user = new User();
user.setName(“风哥1号”);
user.setEmail(“zhangsan@fgedu.net.cn”);

ResponseEntity response = restTemplate.postForEntity(
“/api/users”, user, User.class);

assertEquals(201, response.getStatusCodeValue());
assertNotNull(response.getBody().getId());
assertEquals(“风哥1号”, response.getBody().getName());
}

@Test
public void testGetUser() {
User user = new User();
user.setName(“风哥2号”);
user.setEmail(“lisi@fgedu.net.cn”);
user = userRepository.save(user);

ResponseEntity response = restTemplate.getForEntity(
“/api/users/” + user.getId(), User.class);

assertEquals(200, response.getStatusCodeValue());
assertEquals(“风哥2号”, response.getBody().getName());
}

@Test
public void testUpdateUser() {
User user = new User();
user.setName(“王五”);
user.setEmail(“wangwu@fgedu.net.cn”);
user = userRepository.save(user);

user.setName(“王五更新”);
restTemplate.put(“/api/users/” + user.getId(), user);

ResponseEntity response = restTemplate.getForEntity(
“/api/users/” + user.getId(), User.class);

assertEquals(“王五更新”, response.getBody().getName());
}

@Test
public void testDeleteUser() {
User user = new User();
user.setName(“赵六”);
user.setEmail(“zhaoliu@fgedu.net.cn”);
user = userRepository.save(user);

restTemplate.delete(“/api/users/” + user.getId());

ResponseEntity response = restTemplate.getForEntity(
“/api/users/” + user.getId(), User.class);

assertEquals(404, response.getStatusCodeValue());
}
}

// 运行测试
$ mvn verify

// 输出结果
[INFO] ——————————————————-
[INFO] T E S T S
[INFO] ——————————————————-
[INFO] Running com.fgedu.UserControllerIntegrationTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————

3.2 集成测试最佳实践

  • 使用测试数据库
  • 隔离测试环境
  • 使用测试配置文件
  • 清理测试数据
  • 测试关键业务流程

更多学习教程www.fgedu.net.cn

4. 功能测试

4.1 Selenium功能测试

// Selenium功能测试示例
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import static org.junit.jupiter.api.Assertions.*;

public class LoginFunctionalTest {

private WebDriver driver;

@Test
public void testLoginSuccess() {
ChromeOptions options = new ChromeOptions();
options.addArguments(“–headless”);
driver = new ChromeDriver(options);

try {
driver.get(“https://www.fgedu.net.cn/login”);

WebElement usernameField = driver.findElement(By.id(“username”));
WebElement passwordField = driver.findElement(By.id(“password”));
WebElement loginButton = driver.findElement(By.id(“login-button”));

usernameField.sendKeys(“testuser”);
passwordField.sendKeys(“password123”);
loginButton.click();

WebElement welcomeMessage = driver.findElement(By.id(“welcome-message”));
assertTrue(welcomeMessage.getText().contains(“欢迎”));

} finally {
driver.quit();
}
}

@Test
public void testLoginFailure() {
ChromeOptions options = new ChromeOptions();
options.addArguments(“–headless”);
driver = new ChromeDriver(options);

try {
driver.get(“https://www.fgedu.net.cn/login”);

WebElement usernameField = driver.findElement(By.id(“username”));
WebElement passwordField = driver.findElement(By.id(“password”));
WebElement loginButton = driver.findElement(By.id(“login-button”));

usernameField.sendKeys(“testuser”);
passwordField.sendKeys(“wrongpassword”);
loginButton.click();

WebElement errorMessage = driver.findElement(By.id(“error-message”));
assertTrue(errorMessage.getText().contains(“fgedu或密码错误”));

} finally {
driver.quit();
}
}
}

// 运行测试
$ mvn test

// 输出结果
[INFO] ——————————————————-
[INFO] T E S T S
[INFO] ——————————————————-
[INFO] Running com.fgedu.LoginFunctionalTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————

4.2 功能测试最佳实践

  • 使用页面对象模式
  • 等待页面加载完成
  • 使用有意义的测试数据
  • 清理测试环境
  • 定期维护测试脚本

5. 性能测试

5.1 JMeter性能测试

# JMeter测试计划示例






BASE_URL
https://www.fgedu.net.cn





100
10
false





${BASE_URL}
/api/login
POST
true


{“username”:”testuser”,”password”:”password123″}





false

saveConfig


true
true
true

true
true true true
false
true
true
false
false
false
true
false
false
false
true


results.jtl





# 运行JMeter测试
$ jmeter -n -t performance-test.jmx -l results.jtl -e -o report

# 输出结果
Creating summariser

Created the tree successfully using performance-test.jmx
Starting the test @ Fri Apr 03 10:00:00 CST 2026 (1680500400000)
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump on port 4445
summary + 1 in 00:00:01 = 1.2/s Avg: 123 Min: 123 Max: 123 Err: 0 (0.00%) Active: 100 Started: 100 Finished: 0
summary + 100 in 00:00:10 = 10.0/s Avg: 456 Min: 123 Max: 789 Err: 0 (0.00%) Active: 0 Started: 100 Finished: 100
summary = 100 in 00:00:10 = 10.0/s Avg: 456 Min: 123 Max: 789 Err: 0 (0.00%)
Tidying up … @ Fri Apr 03 10:00:10 CST 2026 (1680500410000)
… end of run

5.2 性能测试最佳实践

  • 设定明确的性能目标
  • 使用生产环境相似的数据量
  • 监控系统资源使用情况
  • 分析性能瓶颈
  • 定期进行性能测试

author:www.itpux.com

6. 安全测试

6.1 OWASP ZAP安全测试

# OWASP ZAP自动化扫描
# 启动ZAP
$ zap.sh -daemon -port 8080 -config api.key=12345

# 创建扫描脚本
#!/bin/bash

ZAP_URL=”http://fgedudb:8080″
API_KEY=”12345″
TARGET_URL=”https://www.fgedu.net.cn”

# 创建新的扫描会话
curl -s “$ZAP_URL/JSON/core/action/newSession/?apikey=$API_KEY”

# 访问目标URL
curl -s “$ZAP_URL/JSON/core/action/accessUrl/?apikey=$API_KEY&url=$TARGET_URL”

# 启动主动扫描
curl -s “$ZAP_URL/JSON/ascan/action/scan/?apikey=$API_KEY&url=$TARGET_URL”

# 等待扫描完成
while true; do
STATUS=$(curl -s “$ZAP_URL/JSON/ascan/view/status/?apikey=$API_KEY” | jq -r ‘.status’)
if [ “$STATUS” == “100” ]; then
break
fi
sleep 5
done

# 获取扫描结果
curl -s “$ZAP_URL/JSON/core/view/alerts/?apikey=$API_KEY” | jq ‘.’

# 生成HTML报告
curl -s “$ZAP_URL/OTHER/core/other/htmlreport/?apikey=$API_KEY” > zap-report.html

# 输出结果示例
{
“alerts”: [
{
“alert”: “Cross Site Scripting (Reflected)”,
“risk”: “High”,
“confidence”: “Medium”,
“url”: “https://www.fgedu.net.cn/search?q=test”,
“description”: “Cross-site Scripting (XSS) is an attack technique…”,
“solution”: “Phase: Architecture and Design…”
},
{
“alert”: “SQL Injection”,
“risk”: “High”,
“confidence”: “High”,
“url”: “https://www.fgedu.net.cn/user?id=1”,
“description”: “SQL injection may be possible…”,
“solution”: “Use parameterized queries…”
}
]
}

6.2 安全测试最佳实践

  • 定期进行安全扫描
  • 修复高危漏洞
  • 使用多种安全工具
  • 进行渗透测试
  • 遵守安全编码规范

更多学习教程公众号风哥教程itpux_com

7. API测试

7.1 Postman API测试

# Postman测试集合示例
{
“info”: {
“name”: “用户API测试”,
“schema”: “https://schema.getpostman.com/json/collection/v2.1.0/collection.json”
},
“item”: [
{
“name”: “创建用户”,
“request”: {
“method”: “POST”,
“header”: [
{
“key”: “Content-Type”,
“value”: “application/json”
}
],
“body”: {
“mode”: “raw”,
“raw”: “{\n \”name\”: \”风哥1号\”,\n \”email\”: \”zhangsan@fgedu.net.cn\”\n}”
},
“url”: {
“raw”: “https://www.fgedu.net.cn/api/users”,
“protocol”: “https”,
“host”: [“www”, “fgedu”, “net”, “cn”],
“path”: [“api”, “users”]
}
},
“event”: [
{
“listen”: “test”,
“script”: {
“exec”: [
“pm.test(‘状态码为201’, function () {“,
” pm.response.to.have.status(201);”,
“});”,
“”,
“pm.test(‘响应包含用户ID’, function () {“,
” var jsonData = pm.response.json();”,
” pm.expect(jsonData).to.have.property(‘id’);”,
“});”,
“”,
“pm.environment.set(‘userId’, pm.response.json().id);”
]
}
}
]
},
{
“name”: “获取用户”,
“request”: {
“method”: “GET”,
“url”: {
“raw”: “https://www.fgedu.net.cn/api/users/{{userId}}”,
“protocol”: “https”,
“host”: [“www”, “fgedu”, “net”, “cn”],
“path”: [“api”, “users”, “{{userId}}”]
}
},
“event”: [
{
“listen”: “test”,
“script”: {
“exec”: [
“pm.test(‘状态码为200’, function () {“,
” pm.response.to.have.status(200);”,
“});”,
“”,
“pm.test(‘fgedu称正确’, function () {“,
” var jsonData = pm.response.json();”,
” pm.expect(jsonData.name).to.eql(‘风哥1号’);”,
“});”
]
}
}
]
}
]
}

# 运行Postman测试
$ newman run user-api-tests.json

# 输出结果
newman

用户API测试

┌─────────────────────────┐
│ created │
└─────────────────────────┘

→ 创建用户
POST https://www.fgedu.net.cn/api/users [201 Created, 234ms]

✓ 状态码为201
✓ 响应包含用户ID

┌─────────────────────────┐
│ completed │
└─────────────────────────┘

→ 获取用户
GET https://www.fgedu.net.cn/api/users/1 [200 OK, 123ms]

✓ 状态码为200
✓ fgedu称正确

┌─────────────────────────────────────────┐
│ summary │
├─────────────────────────────────────────┤
│ total │ 2 │
│ passed │ 4 │
│ failed │ 0 │
├─────────────────────────────────────────┤
│ total time │ 357ms │
└─────────────────────────────────────────┘

7.2 API测试最佳实践

  • 测试所有HTTP方法
  • 验证响应状态码
  • 测试边界条件
  • 测试错误处理
  • 使用环境变量

8. UI测试

8.1 Cypress UI测试

// Cypress UI测试示例
describe(‘用户登录测试’, () => {
beforeEach(() => {
cy.visit(‘https://www.fgedu.net.cn/login’)
})

it(‘成功登录’, () => {
cy.get(‘#username’).type(‘testuser’)
cy.get(‘#password’).type(‘password123’)
cy.get(‘#login-button’).click()

cy.url().should(‘include’, ‘/dashboard’)
cy.get(‘#welcome-message’).should(‘contain’, ‘欢迎’)
})

it(‘登录失败 – 错误密码’, () => {
cy.get(‘#username’).type(‘testuser’)
cy.get(‘#password’).type(‘wrongpassword’)
cy.get(‘#login-button’).click()

cy.get(‘#error-message’).should(‘contain’, ‘fgedu或密码错误’)
})

it(‘登录失败 – 空fgedu’, () => {
cy.get(‘#password’).type(‘password123’)
cy.get(‘#login-button’).click()

cy.get(‘#username-error’).should(‘contain’, ‘请输入fgedu’)
})

it(‘登录失败 – 空密码’, () => {
cy.get(‘#username’).type(‘testuser’)
cy.get(‘#login-button’).click()

cy.get(‘#password-error’).should(‘contain’, ‘请输入密码’)
})
})

// 运行Cypress测试
$ npx cypress run

// 输出结果
====================================================================================================

(Run Starting)

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Cypress: 12.0.0 │
│ Browser: Chrome 112 │
│ Specs: 1 found (login.spec.js) │
└────────────────────────────────────────────────────────────────────────────────────────────────┘

────────────────────────────────────────────────────────────────────────────────────────────────────

Running: login.spec.js (1 of 1)

用户登录测试
✓ 成功登录 (2345ms)
✓ 登录失败 – 错误密码 (1234ms)
✓ 登录失败 – 空fgedu (987ms)
✓ 登录失败 – 空密码 (876ms)

4 passing (5s)

(Results)

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Tests: 4 │
│ Passing: 4 │
│ Failing: 0 │
│ Skipped: 0 │
│ Screenshots: 0 │
│ Video: false │
│ Duration: 5 seconds │
│ Spec Ran: login.spec.js │
└────────────────────────────────────────────────────────────────────────────────────────────────┘

8.2 UI测试最佳实践

  • 使用数据驱动测试
  • 等待元素加载
  • 使用有意义的断言
  • 处理异步操作
  • 定期维护测试脚本

风哥风哥提示:UI测试是验证用户界面功能的重要手段,需要确保测试的稳定性和可靠性。

9. CI/CD集成

9.1 Jenkins集成

# Jenkinsfile示例
pipeline {
agent any

stages {
stage(‘Checkout’) {
steps {
git branch: ‘main’, url: ‘https://github.com/fgedu/myapp.git’
}
}

stage(‘Build’) {
steps {
sh ‘mvn clean package’
}
}

stage(‘Unit Tests’) {
steps {
sh ‘mvn test’
}
post {
always {
junit ‘**/target/surefire-reports/*.xml’
}
}
}

stage(‘Integration Tests’) {
steps {
sh ‘mvn verify’
}
post {
always {
junit ‘**/target/failsafe-reports/*.xml’
}
}
}

stage(‘Performance Tests’) {
steps {
sh ‘jmeter -n -t performance-test.jmx -l results.jtl’
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: ‘report’,
reportFiles: ‘index.html’,
reportName: ‘Performance Report’
])
}
}

stage(‘Security Tests’) {
steps {
sh ‘./security-scan.sh’
}
}

stage(‘Deploy’) {
steps {
sh ‘kubectl apply -f k8s/deployment.yaml’
}
}
}

post {
always {
cleanWs()
}
success {
echo ‘All tests passed!’
}
failure {
echo ‘Some tests failed!’
}
}
}

9.2 GitLab CI集成

# .gitlab-ci.yml示例
stages:
– build
– test
– performance
– security
– deploy

variables:
MAVEN_OPTS: “-Dmaven.repo.local=.m2/repository”

cache:
paths:
– .m2/repository/

build:
stage: build
script:
– mvn clean package
artifacts:
paths:
– target/*.jar
expire_in: 1 hour

unit-tests:
stage: test
script:
– mvn test
artifacts:
reports:
junit: target/surefire-reports/*.xml

integration-tests:
stage: test
script:
– mvn verify
artifacts:
reports:
junit: target/failsafe-reports/*.xml

performance-tests:
stage: performance
script:
– jmeter -n -t performance-test.jmx -l results.jtl
artifacts:
paths:
– results.jtl
expire_in: 1 week

security-tests:
stage: security
script:
– ./security-scan.sh
artifacts:
paths:
– zap-report.html
expire_in: 1 week

deploy:
stage: deploy
script:
– kubectl apply -f k8s/deployment.yaml
only:
– main

9.3 CI/CD集成最佳实践

  • 自动化所有测试阶段
  • 使用并行测试
  • 生成测试报告
  • 设置质量门禁
  • 快速反馈测试结果

学习交流加群风哥QQ113257174

10. 最佳实践

10.1 自动化测试最佳实践

  • 建立测试金字塔
  • 优先自动化关键业务流程
  • 保持测试的独立性
  • 使用有意义的测试数据
  • 定期维护测试脚本
  • 集成到CI/CD流程
  • 监控测试覆盖率
  • 定期评估测试效果

10.2 单元测试最佳实践

  • 每个测试用例只测试一个功能点
  • 使用有意义的测试方法名
  • 保持测试的独立性
  • 覆盖边界条件和异常情况
  • 定期重构测试代码

10.3 集成测试最佳实践

  • 使用测试数据库
  • 隔离测试环境
  • 使用测试配置文件
  • 清理测试数据
  • 测试关键业务流程

10.4 性能测试最佳实践

  • 设定明确的性能目标
  • 使用生产环境相似的数据量
  • 监控系统资源使用情况
  • 分析性能瓶颈
  • 定期进行性能测试

10.5 安全测试最佳实践

  • 定期进行安全扫描
  • 修复高危漏洞
  • 使用多种安全工具
  • 进行渗透测试
  • 遵守安全编码规范
生产环境风哥建议:

  • 建立完善的自动化测试体系
  • 实施测试驱动开发(TDD)
  • 集成到CI/CD流程
  • 定期评估和优化测试策略
  • 培训团队成员的测试技能
  • 使用合适的测试工具
  • 监控测试覆盖率
  • 定期维护测试脚本

author:www.itpux.com

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息