GoDog is the Cucumber implementation for Go: Behaviour-Driven Development (BDD).
You write scenarios in Gherkin (.feature files), then implement the steps in Go.
go test runs the scenarios as normal tests.
1go get github.com/cucumber/godog/cmd/godog@latest
In practice it is a test dependency added to your go.mod.
features/calculator.feature:
1Feature: Calculator
2
3 Scenario: add two numbers
4 Given I have a calculator
5 When I add 3 and 5
6 Then the result should be 8
main_test.go:
1package main
2
3import (
4 "fmt"
5 "testing"
6
7 "github.com/cucumber/godog"
8)
9
10type calculator struct {
11 result int
12}
13
14func (c *calculator) iHaveACalculator() error { return nil }
15
16func (c *calculator) iAdd(a, b int) error {
17 c.result = a + b
18 return nil
19}
20
21func (c *calculator) theResultShouldBe(expected int) error {
22 if c.result != expected {
23 return fmt.Errorf("expected %d, got %d", expected, c.result)
24 }
25 return nil
26}
27
28func InitializeScenario(ctx *godog.ScenarioContext) {
29 c := &calculator{}
30 ctx.Given(`^I have a calculator$`, c.iHaveACalculator)
31 ctx.When(`^I add (\d+) and (\d+)$`, c.iAdd)
32 ctx.Then(`^the result should be (\d+)$`, c.theResultShouldBe)
33}
34
35func TestFeatures(t *testing.T) {
36 suite := godog.TestSuite{
37 ScenarioInitializer: InitializeScenario,
38 Options: &godog.Options{
39 Format: "pretty",
40 Paths: []string{"features"},
41 TestingT: t,
42 },
43 }
44
45 if suite.Run() != 0 {
46 t.Fatal("non-zero status returned, failed to run feature tests")
47 }
48}
1go test -v
Given / When / Then map to ctx.Given / ctx.When / ctx.Then.(...) become arguments of the step function.--godog.format=pretty for human-readable output.