From f3a1f9220a8a5265842f5cb877c4dc6d08f75c68 Mon Sep 17 00:00:00 2001 From: byarbrough Date: Sat, 27 Aug 2022 23:02:31 +0000 Subject: [PATCH] testing: explain using a _test package The existing documentation did not explain the difference between placing a _test.go file in the same package as what is being tested vs. adding it to a separate _test package. This explains the distinction and adds an example. Concept is explained well here: https://stackoverflow.com/a/31443271 Fixes #25223 Change-Id: Iebaba15207d8aa24f0b370d8dd4062eadb504b5c GitHub-Last-Rev: 7f49c5f4624b358af8052272da8ac3240751ada0 GitHub-Pull-Request: golang/go#54160 Reviewed-on: https://go-review.googlesource.com/c/go/+/420415 Reviewed-by: Bryan Mills TryBot-Result: Gopher Robot Reviewed-by: Heschi Kreinick Auto-Submit: Bryan Mills Run-TryBot: Bryan Mills --- src/testing/testing.go | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/testing/testing.go b/src/testing/testing.go index a38b40e38d..5fd153954d 100644 --- a/src/testing/testing.go +++ b/src/testing/testing.go @@ -14,12 +14,19 @@ // Within these functions, use the Error, Fail or related methods to signal failure. // // To write a new test suite, create a file whose name ends _test.go that -// contains the TestXxx functions as described here. Put the file in the same -// package as the one being tested. The file will be excluded from regular +// contains the TestXxx functions as described here. +// The file will be excluded from regular // package builds but will be included when the "go test" command is run. -// For more detail, run "go help test" and "go help testflag". // -// A simple test function looks like this: +// The test file can be in the same package as the one being tested, +// or in a corresponding package with the suffix "_test". +// +// If the test file is in the same package, it may refer to unexported +// identifiers within the package, as in this example: +// +// package abs +// +// import "testing" // // func TestAbs(t *testing.T) { // got := Abs(-1) @@ -28,6 +35,27 @@ // } // } // +// If the file is in a separate "_test" package, the package being tested +// must be imported explicitly and only its exported identifiers may be used. +// This is known as "black box" testing. +// +// package abs_test +// +// import ( +// "testing" +// +// "path_to_pkg/abs" +// ) +// +// func TestAbs(t *testing.T) { +// got := abs.Abs(-1) +// if got != 1 { +// t.Errorf("Abs(-1) = %d; want 1", got) +// } +// } +// +// For more detail, run "go help test" and "go help testflag". +// // # Benchmarks // // Functions of the form -- 2.50.0