Proper package naming for testing with the Go language

前端 未结 4 1316
无人及你
无人及你 2020-12-02 04:08

I have seen several different test package naming strategies within Go and wanted to know what pros and cons of each are and which one I should use.

Strategy

4条回答
  •  春和景丽
    2020-12-02 04:33

    The fundamental difference between the three strategies you've listed is whether or not the test code is in the same package as the code under test. The decision to use package myfunc or package myfunc_test in the test file depends on whether you want to perform white-box or black-box testing.

    There's nothing wrong with using both methods in a project. For instance, you could have myfunc_whitebox_test.go and myfunx_blackbox_test.go.

    Test Code Package Comparison

    • Black-box Testing: Use package myfunc_test, which will ensure you're only using the exported identifiers.
    • White-box Testing: Use package myfunc so that you have access to the non-exported identifiers. Good for unit tests that require access to non-exported variables, functions, and methods.

    Comparison of Strategies Listed in Question

    • Strategy 1: The file myfunc_test.go uses package myfunc — In this case the test code in myfunc_test.go will be in the same package as the code being tested in myfunc.go, which is myfunc in this example.
    • Strategy 2: The file myfunc_test.go uses package myfunc_test — In this case the test code in myfunc_test.go "will be compiled as a separate package, and then linked and run with the main test binary." [Source: Lines 58–59 in the test.go source code]
    • Strategy 3: The file myfunc_test.go uses package myfunc_test but imports myfunc using the dot notation — This is a variant of Strategy 2, but uses the dot notation to import myfunc.

提交回复
热议问题