0
0
Goprogramming~20 mins

Running tests in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go test function?
Consider the following Go test code. What will be printed when running go test?
Go
package main

import (
	"testing"
)

func TestSum(t *testing.T) {
	sum := 2 + 3
	if sum != 5 {
		t.Errorf("Expected 5 but got %d", sum)
	}
	println("TestSum completed")
}
A
FAIL
Expected 5 but got 5
B
TestSum completed
PASS
CNo output
D
PASS
TestSum completed
Attempts:
2 left
💡 Hint
Remember that println outputs to standard output and test failures print error messages.
Predict Output
intermediate
2:00remaining
What error does this Go test produce?
What error message will this Go test produce when run?
Go
package main

import "testing"

func TestFail(t *testing.T) {
	if 1+1 != 3 {
		t.Fatal("Math is broken")
	}
}
A
Math is broken
FAIL
BPASS
Cpanic: Math is broken
DNo output
Attempts:
2 left
💡 Hint
t.Fatal stops the test immediately and prints the message.
🔧 Debug
advanced
2:00remaining
Why does this Go test not run any tests?
Given this Go test file, why does running go test report 'no tests to run'?
Go
package main

import "testing"

func sum(t *testing.T) {
	if 2+2 != 4 {
		t.Error("Wrong sum")
	}
}
ATest functions cannot take parameters
BTest function must return an error
CFunction name must start with 'Test' to be recognized as a test
DMissing import of 'fmt' package
Attempts:
2 left
💡 Hint
Test functions must follow a naming convention to be detected.
📝 Syntax
advanced
2:00remaining
What syntax error does this Go test code produce?
Identify the syntax error in this Go test code snippet.
Go
package main

import "testing"

func TestExample(t *testing.T) {
	if 1 == 1 {
		t.Log("One equals one")
	} else
		t.Error("Math error")
}
ANo syntax error, code runs fine
BSyntax error: missing parentheses around else condition
CSyntax error: missing semicolon after t.Log call
DSyntax error: else must be on the same line as closing brace
Attempts:
2 left
💡 Hint
In Go, else must be on the same line as the closing brace of if block.
🚀 Application
expert
2:00remaining
How many tests are run by this Go test file?
Given this Go test file, how many tests will go test run?
Go
package main

import "testing"

func TestOne(t *testing.T) {}

func TestTwo(t *testing.T) {}

func testThree(t *testing.T) {}

func TestFour() {}

func TestFive(t *testing.T) {
	t.Run("Subtest", func(t *testing.T) {})
}
A3
B4
C5
D2
Attempts:
2 left
💡 Hint
Only functions starting with 'Test' and taking *testing.T run as tests. Subtests count as part of parent test.