What is internal and external testing?
Let's show a example
package operator
func Add(a, b int) int {
return a + b
}
func subtract(a, b int) int {
return a - b
}
Internal test is that the test cases belongs to the package we want to test
package operator // same package
import (
"testing"
)
func Test_Add(t *testing.T) {
if got := Add(1, 1); got != 2 {
t.Errorf("Add(%v, %v) = %v, want %v", 1, 2, got, 2)
}
}
func Test_subtract(t *testing.T) {
if got := subtract(1, 1); got != 2 {
t.Errorf("Add(%v, %v) = %v, want %v", 1, 2, got, 2)
}
}
External test is that the test cases locate in different package. The functions to test need to be exported,
package operator_test //different package
import (
"awesomeProject/operator" // package needs to import here
"testing"
)
func Test_Add(t *testing.T) {
if got := operator.Add(1, 1); got != 2 {
t.Errorf("Add(%v, %v) = %v, want %v", 1, 2, got, 2)
}
}
func Test_subtract(t *testing.T) {
// get error here, because operator.subtract can't be exported
if got := operator.subtract(1, 1); got != 2 {
t.Errorf("Add(%v, %v) = %v, want %v", 1, 2, got, 2)
}
}
By internal testing, you can directly access all thing in your package, including unexported var,func,struct.
By external testing, you can only test exported things.
Internal testing is better, because we could test everything in the package?
The answer is No, if you come from java/c# or other OOP language, you may have seen some discussion like "should I test private method?","how can I test private method?". The conclusion is that you should test public methods only, because test is to simulate how other users use your method or how external project calls your package.
Unexported things are not under testing?
Come back to golang, right, exported method/function/struct is the important thing you should test, how other gophers/projects use your package.
Then you may ask how about unexported things, they're not under testing. The answer is also No. Actually all unexported things should be covered by exported things, otherwise the unexported things are redundant code.(because no one call them)
Conclusion
Just see some discussion, so write down this article for new gophers have no idea which to use. Maybe there're some cases that internal testing is necessary, but external testing is to choose in the general case.
Top comments (0)