minitest是一套Ruby的测试工具,支持TDDBDD、Mock和基准测试。minitest使用最简单的Ruby语法,没有自己定义一套。因此上手非常简单。

和另一个测试框架rspec相比引用官方文档的一句话

minitest doesn’t reinvent anything that ruby already provides, like: classes, modules, inheritance, methods. This means you only have to learn ruby to use minitest and all of your regular OO practices like extract-method refactorings still apply.

测试用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# cat.rb
class Cat
TOYS = [
"sofa",
"teddy"
]
def meow
"Meow~!"
end

def scratch(target)
"YES!"
end

def favorite_toy()
"teddy"
end
end
单元测试
minitest风格

在定义一个以Test开始的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require "minitest/autorun"
require_relative "cat"

class TestCat < Minitest::Test
def setup
@cat = Cat.new
end

def test_meow
# 相等
assert_equal "Meow~!", @cat.meow
end

def test_toys_is_array
# 断言类型
assert_kind_of Array, Cat::TOYS
end

def test_favorite_toy
# 断言是否包括
assert_includes Cat::TOYS, @cat.favorite_toy
end

def test_toys_empty
# 断言非空,refute是取反的意思
refute_empty Cat::TOYS
end

def test_not_woof
# 断言匹配
refute_match /^woof/i, @cat.meow
end

def test_raises_error
# 测试抛出错误
assert_raises "There is no toy here" do
@cat.scratch("teddy")
end
end

def test_that_will_be_skipped
# 跳过
skip "test this later"
end
end
specs风格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
require "minitest/autorun"
require "minitest/spec"
require_relative "cat"

describe Cat do
before do
@cat = Cat.new
end

describe "#meow" do
it "must respond meow" do
@cat.meow.must_equal "Meow~!"
end

it "predefined toys is array" do
@cat.assert_kind_of Array, Cat::TOYS
end

it "test favorite toy" do
@cat.assert_includes Cat::TOYS, @cat.favorite_toy
end

it "test toys empty" do
@cat.refute_empty Cat::TOYS
end

it "test raises error" do
@cat.assert_raises "There is no toy here" do
@cat.scratch("teddy")
end
end

it "test that will be skipped" do
skip "test this later"
end
end
end

Minitest::Test提供了几个生命周期的钩子,分别是

  • before_setup

  • setup

  • after_setup

  • before_teardown

  • teardown

  • after_teardown

一般开发只用setupteardown就够用了,几个before_*after_*是用于minitest扩展的。

以上只列出了常用的几个assertion,查看所有的查阅Minitest Assertions API

此外,MiniTest还提供了BenchmarksMocks,后续更新……