Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test unexported struct field in a different package in go?

I have a package that creates objects with a factory. The structs have unexported fields, e.g.:

package fetcher
type GitFetcher struct {
    uri    string
}

I have another package that parses some config files and then builds another object which uses the above objects:

package config
type Source struct {
    fetcher    GitFetcher
}

I'm trying to test my config package. I want to build some expected objects, but since my tests are in config and my GitFetcher is in fetcher I can't just create the objects I want, e.g.:

package config
expected := GitFetcher{
    uri: "example.com/repo.git"      // doesn't work. Field isn't exported.
}

How can I build objects across packages for testing like this? I don't want to use the fetcher factory method since the parameters it takes aren't straightforward.

like image 202
jbrown Avatar asked Oct 14 '25 14:10

jbrown


2 Answers

How to test unexported [...] a different package in go?

Not at all. Undoable, do not try.

(If the unexported thing has an exported method, then you can call this method.)

like image 125
Volker Avatar answered Oct 17 '25 11:10

Volker


There is no direct way to achieve this. You have multiple options to achieve something similar, all with their own tradeoffs. It's up to you to decide which tradeoff is most acceptable in your case.

In general, I would try them in this order:

  1. Make package config depend on an interface instead of on the GitFetcher struct. That way you can mock GitFetcher in your tests.
  2. Add an additional factory method specifically for tests that can construct GitFetcher more easily.
  3. Make the unexported field exported.
  4. Simply combine the packages. That way you can access the unexported fields of both objects in your tests.
like image 20
Vincent van der Weele Avatar answered Oct 17 '25 10:10

Vincent van der Weele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!