Learn to Code in 5 Minutes a Day: Lesson 5
By Code with ADHD
- 3 minutes read - 461 wordsSession 4 Solution:
hello_test.go
func TestHelloInigoMontoya(t *testing.T) {
result := hello("inigo montoya")
expected := "hello, inigo montoya"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
func TestHelloDuaLipa(t *testing.T) {
result := hello("Dua Lipa")
expected := "hello, Dua Lipa"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
func TestHelloDarthVader(t *testing.T) {
result := hello("Darth Vader")
expected := "hello, Darth Vader"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
func TestHelloDarthVaderNegativeTest(t *testing.T) {
result := hello("Darth Vader")
notExpected := "Luke, I am your Father."
if result == notExpected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, notExpected)
}
}
When I test my program I see that all the tests passed.
go test
PASS
ok hello 0.076s
Does your code pass the above tests? Or did you write one test like this:
func TestHello(t *testing.T) {
result := hello("inigo montoya")
expected := "hello, inigo montoya"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
result = hello("Dua Lipa")
expected = "hello, Dua Lipa"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
result = hello("Darth Vader")
notExpected := "Luke, I am your Father."
if result == notExpected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, notExpected)
}
}
Either way is fine. Don’t just blindly copy things you don’t understand and expect to learn. If you aren’t confident you understand, see if you can delete what you’ve done so far and recreate it.
Today’s Lesson: go fmt
One thing we haven’t covered yet is formatting your code.
The nice thing about go compared to other programming languages is it has a built-in formatter. You don’t have to worry too much about spacing and indentation. Go can take care of that for you and give you errors if you make mistakes. One of the biggest challenges you’ll have to face as a new programmer (or even an experienced programmer learning a new language) is how to interpret error messages. So let’s spend a little time seeing what go fmt can tell us.
In your hello.go file, what happens if you change the hello function to look like this:
func hello(name string) string { greeting := "hello, " + name return greeting }
Does it give you an error when you run go fmt?
It should. Can you figure out how to fix the error? There are actually a couple of ways to fix it. Play with that for a few minutes and if the errors don’t make sense to you, practice your google skills to see if other people have run into similar errors.