Re: [go-nuts] Testing private (unexported) functions

3,529 views
Skip to first unread message

minux

unread,
Nov 1, 2012, 4:54:45 PM11/1/12
to Sebastian Es, golan...@googlegroups.com

On Fri, Nov 2, 2012 at 3:26 AM, Sebastian Es <seba...@hypenode.com> wrote:
I want to test unexported methods in package. According to Go source tests are grouped in <package_name>_test package so unexported functions are invisible here. The only way to do this is putting them in the same package. How to bite this?
You can add a file to export these unexported method just for tests.

e.g. a file export_test.go
package somepkg

var ExportedFunc = privateFunc

Rémy Oudompheng

unread,
Nov 1, 2012, 4:58:02 PM11/1/12
to Sebastian Es, golan...@googlegroups.com
On 2012/11/1 Sebastian Es <seba...@hypenode.com> wrote:
> Hello,
>
> I want to test unexported methods in package. According to Go source tests
> are grouped in <package_name>_test package so unexported functions are
> invisible here. The only way to do this is putting them in the same package.
> How to bite this?

Most package put tests in the same package as code (but in *_test.go
files). Using the packagename_test package is only necessary when you
have circular imports problems, which is not very common.

So just use "package <packagename>" in your test files unless it
causes a problem. The tests will be able to access all private
identifiers.

Rémy.

Dave Cheney

unread,
Dec 20, 2012, 8:01:36 PM12/20/12
to johan...@gmail.com, golan...@googlegroups.com, Sebastian Es
Files ending in _test.go are only compiled in to the test executable.  Have a look at the export_test.go file in net/http. 

On 21/12/2012, at 8:46, johan...@gmail.com wrote:

@Rémy: But then how to keep those tests out of the .a (or exe) file when building or installing ?
--
 
 

Volker Dobler

unread,
Dec 21, 2012, 4:03:07 AM12/21/12
to golan...@googlegroups.com, johan...@gmail.com, Sebastian Es


Am Freitag, 21. Dezember 2012 09:32:46 UTC+1 schrieb johan...@gmail.com:
I have my tests in a separate folder in a <package>_test package (wanting to avoid clutter in the <package> folder).

Don't do that. Keep your tests and code together like it is done
in the standard library.
 
Putting a export_test.go file in the <package> folder does not work, as it is not compiled into the package, and it is neither part of the <package>_test package neither then. I have to give it a regular name like <package>-test.go, but then it is included in the package .a, so exporting those functions unwanted. Any ideas for how to solve that situation (apart from moving the tests in the <package> folder) ?

Not sure if this can be solved at all, but again: Just stick to the way testing is 
intended: Keep the _test.go files in the same folder as your package 
implementation (and use the same package name). This is actually much
saner than the Java way of separating what belongs together into main and test.

V.
Reply all
Reply to author
Forward
0 new messages