0
0
Goprogramming~10 mins

Running tests in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the testing package.

Go
import [1]
Drag options to blanks, or click blank then click option'
A"fmt"
B"os"
C"testing"
D"net/http"
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'fmt' instead of 'testing'.
Forgetting to import any package.
2fill in blank
medium

Complete 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'
At
Btest
CT
Dctx
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'T' as parameter name.
Using unrelated parameter names like 'ctx'.
3fill in blank
hard

Fix 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'
Afmt
Bt
Clog
Dtesting
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fmt' or 'log' instead of 't' to report errors.
Using 'testing' package name instead of the parameter.
4fill in blank
hard

Fill 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'
Atest
Brun
Cmain.go
Dsum_test.go
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'run' instead of 'test'.
Specifying a non-test file like 'main.go'.
5fill in blank
hard

Fill 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'
Atc
Btest
Dt
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using 't' as loop variable which conflicts with testing.T.