# Unknwon/wuwen.org

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

# goconvey - 课时 1：优雅的单元测试 #9

Open
opened this Issue Nov 22, 2016 · 0 comments

1 participant
Owner

## 库简介

Go 语言虽然自带单元测试功能，在 GoConvey 诞生之前也出现了许多第三方辅助库。但没有一个辅助库能够像 GoConvey 这样优雅地书写代码的单元测试，简洁的语法和舒适的界面能够让一个不爱书写单元测试的开发人员从此爱上单元测试。

## 下载安装

`gopm get github.com/smartystreets/goconvey`

`go get github.com/smartystreets/goconvey`

## 基本使用方法

### 书写代码

```package goconvey

import (
"errors"
)

func Add(a, b int) int {
return a + b
}

func Subtract(a, b int) int {
return a - b
}

func Multiply(a, b int) int {
return a * b
}

func Division(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("被除数不能为 0")
}
return a / b, nil
}```

```package goconvey

import (
"testing"

. "github.com/smartystreets/goconvey/convey"
)

func TestAdd(t *testing.T) {
Convey("将两数相加", t, func() {
So(Add(1, 2), ShouldEqual, 3)
})
}

func TestSubtract(t *testing.T) {
Convey("将两数相减", t, func() {
So(Subtract(1, 2), ShouldEqual, -1)
})
}

func TestMultiply(t *testing.T) {
Convey("将两数相乘", t, func() {
So(Multiply(3, 2), ShouldEqual, 6)
})
}

func TestDivision(t *testing.T) {
Convey("将两数相除", t, func() {

Convey("除以非 0 数", func() {
num, err := Division(10, 2)
So(err, ShouldBeNil)
So(num, ShouldEqual, 5)
})

Convey("除以 0", func() {
_, err := Division(10, 0)
So(err, ShouldNotBeNil)
})
})
}```

`Convey` 语句同样可以无限嵌套，以体现各个测试用例之间的关系，例如 `TestDivision` 函数就采用了嵌套的方式体现它们之间的关系。需要注意的是，只有最外层的 `Convey` 需要传入变量 t，内层的嵌套均不需要传入。

### 运行测试

```=== RUN TestAdd

将两数相加 ✔

1 assertion thus far

--- PASS: TestAdd (0.00 seconds)
=== RUN TestSubtract

将两数相减 ✔

2 assertions thus far

--- PASS: TestSubtract (0.00 seconds)
=== RUN TestMultiply

将两数相乘 ✔

3 assertions thus far

--- PASS: TestMultiply (0.00 seconds)
=== RUN TestDivision

将两数相除
除以非 0 数 ✔✔
除以 0 ✔

6 assertions thus far

--- PASS: TestDivision (0.00 seconds)
PASS
ok  	github.com/Unknwon/go-rock-libraries-showcases/lectures/03-goconvey/class1/sample/goconvey	0.009s```

## 使用 GoConvey 编写测试用例的包

### Unknwon added Go GoConvey labels Nov 22, 2016

to join this conversation on GitHub. Already have an account? Sign in to comment