Last active
March 11, 2016 20:51
-
-
Save vaskoz/e38b3c6525b012fa6b06 to your computer and use it in GitHub Desktop.
Test Coverage Question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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