тесты

This commit is contained in:
badkaktus 2019-10-11 16:16:53 +03:00
parent 4d63d4ae43
commit e5ae825999
2 changed files with 26 additions and 25 deletions

View File

@ -61,7 +61,7 @@ Epoch
Пути к файлам (File Paths) Пути к файлам (File Paths)
Директории (Directories) Директории (Directories)
Временные файлы и директории (Temporary Files and Directories) Временные файлы и директории (Temporary Files and Directories)
Testing Тестирование (Testing)
Command-Line Arguments Command-Line Arguments
Command-Line Flags Command-Line Flags
Command-Line Subcommands Command-Line Subcommands

View File

@ -1,11 +1,12 @@
// Unit testing is an important part of writing // Unit тестирование является важной частью написания
// principled Go programs. The `testing` package // правильных программ Go. Пакет тестирования `testing`
// provides the tools we need to write unit tests // предоставляет инструменты, необходимые для
// and the `go test` command runs tests. // написания unit тестов, а команда `go test` запускает
// тесты.
// For the sake of demonstration, this code is in package // Для наглядности этот код находится в `main` пакете,
// `main`, but it could be any package. Testing code // но это может быть любой пакет. Тестовый код обычно
// typically lives in the same package as the code it tests. // находится в том же пакете, что и код, который он тестирует.
package main package main
import ( import (
@ -13,11 +14,11 @@ import (
"testing" "testing"
) )
// We'll be testing this simple implementation of an // Мы будем тестировать эту простую реализацию
// integer minimum. Typically, the code we're testing // целочисленного минимума. Обычно код, который мы
// would be in a source file named something like // тестируем, находится в исходном файле с именем
// `intutils.go`, and the test file for it would then // что-то вроде `intutils.go`, а тестовый файл для
// be named `intutils_test.go`. // него будет называться `intutils_test.go`.
func IntMin(a, b int) int { func IntMin(a, b int) int {
if a < b { if a < b {
return a return a
@ -26,22 +27,22 @@ func IntMin(a, b int) int {
} }
} }
// A test is created by writing a function with a name // Тест создается путем написания функции с именем,
// beginning with `Test`. // начинающимся с `Test`.
func TestIntMinBasic(t *testing.T) { func TestIntMinBasic(t *testing.T) {
ans := IntMin(2, -2) ans := IntMin(2, -2)
if ans != -2 { if ans != -2 {
// `t.Error*` will report test failures but continue // `t.Error*` сообщит об ошибках теста, но продолжит
// executing the test. `t.Fail*` will report test // выполнение теста. `t.Fail*` сообщит об ошибках
// failures and stop the test immediately. // теста и немедленно остановит тест.
t.Errorf("IntMin(2, -2) = %d; want -2", ans) t.Errorf("IntMin(2, -2) = %d; want -2", ans)
} }
} }
// Writing tests can be repetitive, so it's idiomatic to // Написание тестов может быть повторяющимся, поэтому
// use a *table-driven style*, where test inputs and // идиоматично использовать *table-driven style*, где тестовые
// expected outputs are listed in a table and a single loop // входы и ожидаемые выходы перечислены в таблице, а один
// walks over them and performs the test logic. // цикл проходит по ним и выполняет тестовую логику.
func TestIntMinTableDriven(t *testing.T) { func TestIntMinTableDriven(t *testing.T) {
var tests = []struct { var tests = []struct {
a, b int a, b int
@ -55,9 +56,9 @@ func TestIntMinTableDriven(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
// t.Run enables running "subtests", one for each // t.Run позволяет запускать «подтесты», по одному
// table entry. These are shown separately // для каждой записи таблицы. Они показываются
// when executing `go test -v`. // отдельно при выполнении `go test -v`.
testname := fmt.Sprintf("%d,%d", tt.a, tt.b) testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
t.Run(testname, func(t *testing.T) { t.Run(testname, func(t *testing.T) {
ans := IntMin(tt.a, tt.b) ans := IntMin(tt.a, tt.b)