首页 > 解决方案 > 使用带有 GoDog 测试框架的断言库

问题描述

我使用Cucumber GoDog作为 gRPC 微服务测试的 BDD 测试框架。GoDog 不附带任何断言助手或实用程序。

这里有没有人有采用任何现有断言库(如Testify / GoMega with GoDog)的经验?

据我所知,GoDog 不能在此基础上工作,go test这就是为什么我猜想采用go test我提到的任何基于断言库都具有挑战性。但我仍然想在这里检查是否有人有这样做的经验。

标签: gotestingcucumberassertion

解决方案


这是使用 Testify 的基本概念验证:

package bdd
import (
    "fmt"
    "github.com/cucumber/godog"
    "github.com/stretchr/testify/assert"
)
type scenario struct{}
func (_ *scenario) assert(a assertion, expected, actual interface{}, msgAndArgs ...interface{}) error {
    var t asserter
    a(&t, expected, actual, msgAndArgs...)
    return t.err
}
func (sc *scenario) forcedFailure() error {
    return sc.assert(assert.Equal, 1, 2)
}
type assertion func(t assert.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
type asserter struct {
    err error
}
func (a *asserter) Errorf(format string, args ...interface{}) {
    a.err = fmt.Errorf(format, args...)
}
func FeatureContext(s *godog.Suite) {
    var sc scenario
    s.Step("^forced failure$", sc.forcedFailure)
}
Feature: forced failure
  Scenario: fail
    Then forced failure

这里的关键是实现 Testify 的assert.TestingT接口。


推荐阅读