title: Unit test of a singleton accessed as an interface
body: <p>I have a singleton in my application, but it's published not as a struct directly, but as an interface (because I want to be able to dynamically select the particular implementation upon singleton initialization). Here's the code:</p>
  
  <pre><code>var once sync.Once
  var instance defaultConfiguration
  
  type Configuration interface {
      GetFoo() string
  }
  
  type defaultConfiguration struct {
  }
  
  func (dc defaultConfiguration) GetFoo() string {
      return "foo"
  }
  
  func NewConfiguration() Configuration {
      once.Do(func() {
          instance = defaultConfiguration{}
      })
      return instance
  }
  </code></pre>
  
  <p>Then I decided to write a unit-test that would check that <code>NewConfiguration()</code> will actually return the same instance each time:</p>
  
  <pre><code>func TestNewConfigurationSameInstance(t *testing.T) {
      configuration1 := NewConfiguration()
      configuration2 := NewConfiguration()
      if &amp;configuration1 != &amp;configuration2 {
          t.Error()
      }
  }
  </code></pre>
  
  <p>I thought it would make sense to compare the addresses of the returned instances, however, this test fails.</p>
  
  <p>Then I thought, well, maybe I have to return a pointer to an instance, so I've changed the code to look like this:</p>
  
  <pre><code>func NewConfiguration() *Configuration {
      once.Do(func() {
          instance = defaultConfiguration{}
      })
      return &amp;instance
  }
  </code></pre>
  
  <p>But this doesn't even compile: it fails with the error message </p>
  
  <blockquote>
    <p>cannot use &amp;instance (type *defaultConfiguration) as type *Configuration in return argument:
        *Configuration is pointer to interface, not interface</p>
  </blockquote>
  
  <p>And I've got very confused. Why can't I return a pointer to an interface? Or, why returning <code>defaultConfiguration</code> as <code>Configuration</code> is valid, but returning <code>*defaultConfiguration</code> as <code>*Configuration</code> is not?</p>
  
  <p>And, after all, what is the proper unit-test for my use-case? </p>