Go · Chapter 11 of 26

Testing

By the end of this chapter you can write tests in _test.go files and run them with go test, report failures with t.Errorf and t.Fatalf, write table tests with subtests and run one of them with -run, read -v and -cover, write test helpers with t.Helper, and, above all, write tests that fail when the code is wrong. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Real programs
  • 4 tasks
  • Go
  • In the all labs plan

The first 2 chapters of Go are free. This one comes with the all labs plan.

Why you need this

Pooja's billing rule is one line: (wh*paisePerKWh + 500) / 1000. Last year, before Go, a cleanup changed it to wh*paisePerKWh / 1000, which looks the same, compiles, and drops the fraction of a paisa from every session. On a day of 3,600 sessions, 820 of Wednesday's costs end in half a paisa or more, and each would have lost one. Nothing crashed; the bills were just a little wrong, and finance found it a month later.

So far you have checked your code by running main and reading what it printed. That works once, for you, today. It does not run again when Joseph changes the rounding next month, and it does not tell anyone which line broke. A test is code that checks code: it runs in a second, every time, and fails loudly with the case that broke. Go has it built in: a package called testing and the command go test.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    cost_test.go: a table test that catches a broken Cost

    billing.go holds the code under test: Cost(wh, paisePerKWh int) int returns wh times paisePerKWh divided by 1000, rounded to the nearest paisa, half a paisa up (Cost(17385, 2000) is 34770).

    In cost_test.go, write a table test for Cost: a slice of cases (a struct with the watt-hours, the rate and the cost you expect) and one loop over it that calls Cost and reports a wrong result with t.Errorf or t.Fatalf.

    The Check runs cost_test.go on its own with billing.go: it must pass with the right Cost and fail with each of three broken ones: one that drops the fraction of a paisa (truncates), one that always rounds up, and one that rounds exactly half a paisa down instead of up. The last one differs from the right Cost only when the cost ends in exactly half a paisa, which happens with a rate of 900 paise a kWh and the right watt-hours. cost_test.go must not use helpers from your other test files.

  2. Task 2

    split_test.go: subtests that catch a broken Split

    Split(paise int) (rupees, rest int) in billing.go turns paise into whole rupees and the paise left over: Split(34770) is 347 and 70.

    In split_test.go, write TestSplit with one subtest a case: t.Run with a name (for example "34770") and a function that checks both of Split's results.

    The Check runs split_test.go on its own with billing.go: it must pass with the right Split and fail with each of three broken ones: one that returns rupees and paise swapped, one whose paise are only the last digit (paise % 10), and one whose rupees are paise / 1000. Then go test -v lists your subtests, and go test -run TestSplit/34770 runs one.

  3. Task 3

    reading_test.go: a test that catches a broken ParseReading

    ParseReading(line string) (string, int, error) in billing.go reads a charger's line, its id and its meter in watt-hours: "C1042,18437" gives C1042, 18437 and a nil error. A line with no comma, an empty id, watt-hours that are not a whole number, or negative watt-hours gives an error that wraps ErrBadReading.

    In reading_test.go, test it: a good line and its two values, and bad lines whose error must satisfy errors.Is(err, ErrBadReading). Write at least one helper function that calls t.Helper().

    The Check runs reading_test.go on its own with billing.go: it must pass with the right ParseReading and fail with each of three broken ones: one that accepts negative watt-hours ("C1042,-5"), one whose errors do not wrap ErrBadReading, and one that accepts an empty id (",18437").

  4. Task 4 · interview question

    Interview: rate_test.go, one table instead of copies

    RateFor(kind string) (int, error) in billing.go returns the paise a kWh of a kind: AC7 1400, DC30 2000, DC60 2400, LEV3 900; any other kind returns 0 and an error that wraps ErrUnknownKind. Tenzin tested it by copying one test function a kind, and stopped after two.

    Replace his tests with exactly one test function in rate_test.go: a table of cases with all four kinds and one unknown kind, a loop over it, and t.Run for each case.

    The Check runs rate_test.go on its own with billing.go: it must pass with the right RateFor and fail with each of three broken ones: one that gives DC60 2000, one that gives LEV3 1400, and one that gives an unknown kind 0 and no error.

    Joseph will ask: why table tests? What does a new case cost in Tenzin's way, and in yours?

What you will learn

  • _test.go files and go test: where tests live and how they run.
  • **func TestX(t \*testing.T)**: the shape of a test.
  • t.Errorf and t.Fatalf: report and go on, or report and stop.
  • Table tests: many cases, one loop.
  • t.Run subtests, and go test -run and -v.
  • go test -cover, and t.Helper for helpers.

More in Real programs

Build "Testing" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Go are free. This one comes with the all labs plan.