Go ---- godog的使用

本文介绍如何使用 godog 进行行为驱动开发 (BDD),包括安装、配置及实现一个简单的吃东西功能测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

godog和go test做的是一样的事,都是测试代码的。只是换了一种形式。

godog是Golang的官方Cucumber BDD框架,它将规范和测试文档合并为一个有凝聚力的整体,使用Gherkin格式的场景,格式为Given,When,Then。

使用

目的:我们要测试一个吃东西的功能是否已经实现。

使用go get 安装

go get github.com/cucumber/godog/cmd/godog@v0.12.0

或是是安装二进制文件使用go install

go install github.com/cucumber/godog/cmd/godog@latest

创建一个feature文件夹,并在该文件夹中创建godogs.feature文件,内容如下

Feature: eat godogs
  In order to be happy
  As a hungry gopher
  I need to be able to eat godogs

  Scenario: Eat 5 out of 12
    Given there are 12 godogs
    When I eat 5
    Then there should be 7 remaining

然后在控制台使用godog run

会出现如下内容

Feature: eat godogs
  In order to be happy
  As a hungry gopher
  I need to be able to eat godogs

  Scenario: Eat 5 out of 12          # features/godogs.feature:6
    Given there are 12 godogs
    When I eat 5
    Then there should be 7 remaining

1 scenarios (1 undefined)
3 steps (3 undefined)
220.129µs

You can implement step definitions for undefined steps with these snippets:

func iEat(arg1 int) error {
   
        return godog.ErrPending
}

func thereAreGodogs(arg1 int) error {
   
        return godog.ErrPending
}

func thereShouldBeRemaining(arg1 int) error {
   
        return godog.ErrPending
}

func InitializeScenario(ctx *godog.ScenarioContext) {
   
        ctx.Step(`^I eat (\d+)$`, iEat)
        ctx.Step(`^there are (\d+) godogs$`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值