Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the testing package.
Go
import [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'fmt' instead of 'testing'.
Forgetting to import any package.
✗ Incorrect
The testing package is imported with "testing" to write test functions.
2fill in blank
mediumComplete the code to define a test function for Go testing.
Go
func TestSum([1] *testing.T) { } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'T' as parameter name.
Using unrelated parameter names like 'ctx'.
✗ Incorrect
The test function receives a pointer to testing.T, commonly named 't'.
3fill in blank
hardFix the error in the test function to fail the test when sum is incorrect.
Go
if sum := 2 + 2; sum != 5 { [1].Errorf("Expected 5 but got %d", sum) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fmt' or 'log' instead of 't' to report errors.
Using 'testing' package name instead of the parameter.
✗ Incorrect
The test function uses the parameter 't' to report errors with Errorf.
4fill in blank
hardFill both blanks to run the test with go test and specify the test file.
Go
go [1] -v [2]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'run' instead of 'test'.
Specifying a non-test file like 'main.go'.
✗ Incorrect
The command 'go test -v sum_test.go' runs tests verbosely in the specified test file.
5fill in blank
hardFill all three blanks to write a table-driven test loop over test cases.
Go
tests := []struct {
name string
input int
want int
}{
{"test1", 1, 2},
{"test2", 2, 4},
}
for _, [1] := range tests {
t.Run([2].name, func(t *testing.T) {
got := double([3].input)
if got != [3].want {
t.Errorf("got %d, want %d", got, [3].want)
}
})
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using 't' as loop variable which conflicts with testing.T.
✗ Incorrect
The loop variable is commonly named 'tc' for test case; it is used to access fields in the test run.