Java 里的 JUnit
写 Java 的人几乎都用过 JUnit,它是最经典的单元测试框架之一。比如你写了个工具类,用来计算两个数的和,想确认结果对不对,就可以用 JUnit 写个测试方法跑一下。
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
只要加个 @Test 注解,运行这个方法就能看到是否通过。简单直接,适合刚入门的同学上手。
Python 的 pytest 和 unittest
Python 自带一个叫 unittest 的库,设计思路来自 JUnit,功能完整但写法稍微啰嗦一点。很多人更喜欢用 pytest,语法更简洁,写起来像在写普通函数。
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
就这么几行代码,不用继承类、不用复杂结构,直接用 assert 就能断言结果。装上 pytest 跑一遍,失败了会清楚告诉你哪一行出了问题。
JavaScript 测试常用 Jest
前端项目现在基本离不开 Jest,尤其配合 React 使用特别顺手。它自带断言、模拟函数、快照测试等功能,开箱即用。
function sum(a, b) {
return a + b;
}
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Jest 运行速度快,还能测异步代码,比如接口请求这类场景也能覆盖到。很多团队把 Jest 集成进 CI 流程,每次提交代码自动跑一遍测试,避免改出 bug 自己还不知道。
C# 开发者常用 NUnit 和 MSTest
在 .NET 生态里,NUnit 和 MSTest 是主流选择。MSTest 是微软官方推出的,和 Visual Studio 深度集成,点几下鼠标就能生成测试用例。NUnit 更灵活一些,支持更多高级特性,社区也比较活跃。
[TestMethod]
public void Add_ShouldReturnCorrectSum()
{
var result = Calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
这种写法看起来和 JUnit 很像,说明不同语言的测试框架其实思路都差不多:标记测试方法,执行并验证结果。
Go 语言用内置 testing 包
Go 不搞额外依赖,直接在标准库里提供了 testing 包。写测试的时候只要文件名以 _test.go 结尾,里面写 Test 开头的函数就行。
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("期望 5,实际 %d", result)
}
}
命令行敲 go test 就能跑起来。虽然功能不如其他框架花哨,但够用、轻量,符合 Go 的整体风格。