Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Last active March 11, 2016 20:51
Show Gist options
  • Save vaskoz/e38b3c6525b012fa6b06 to your computer and use it in GitHub Desktop.
Save vaskoz/e38b3c6525b012fa6b06 to your computer and use it in GitHub Desktop.
Test Coverage Question
package main
import (
"log"
"os"
)
// METHOD1
// Typical Method
func GetHostname() string {
name, err := os.Hostname()
if err != nil {
log.Fatalln("Could not get hostname", err)
}
if name == "" {
log.Println("WARNING: Hostname is blank!")
}
return name
}
// METHOD2
type HostnameResolver interface {
Name() (string, error)
}
type osHostnameResolver struct {
resolver func() (string, error)
}
func (hr *osHostnameResolver) Name() (string, error) {
return hr.resolver()
}
// Dependency Injected and Dependency Inverted
func GetHostnameDI(hr HostnameResolver) string {
name, err := hr.Name()
if err != nil {
log.Println("Could not get hostname", err)
}
if name == "" {
log.Println("WARNING: Hostname is blank!")
}
return name
}
package main
import (
"errors"
"os"
"testing"
)
func TestGetHostname(t *testing.T) {
_ = GetHostname()
}
func TestGetHostnameDIwithOS(t *testing.T) {
_ = GetHostnameDI(&osHostnameResolver{os.Hostname})
}
func TestGetHostnameDIwithBlank(t *testing.T) {
_ = GetHostnameDI(&osHostnameResolver{
func() (string, error) {
return "", nil
},
})
}
func TestGetHostnameDIwithError(t *testing.T) {
_ = GetHostnameDI(&osHostnameResolver{
func() (string, error) {
return "", errors.New("Vasko doesn't want to give you the hostname")
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment