如何在不同的包中测试未导出的struct字段?

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.

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.)

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.