标签: testify

AssertCalled总是以testify库失败

我正在使用testify来测试我的代码,我想检查函数是否被调用.

我正在做以下事情:

type Foo struct {
    mock.Mock
}

func (m Foo) Bar() {

}

func TestFoo(t *testing.T) {
    m := Foo{}
    m.Bar()
    m.AssertCalled(t, "Bar")
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

Error:      Should be true
Messages:   The "Bar" method should have been called with 0 argument(s), but was not.

mock.go:419: []
Run Code Online (Sandbox Code Playgroud)

我调用函数"Bar"并立即询问它是否被调用但返回false.我究竟做错了什么?测试函数是否通过testify调用的正确方法是什么?

go testify

5
推荐指数
1
解决办法
1670
查看次数

我如何在 Go 中模拟 Stripe?

我正在尝试模拟 Stripe 进行一些测试。

//testify mock
type Backend struct {
    mock.Mock
}

func (s Backend) Call(method, path, key string, params stripe.ParamsContainer, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) SetMaxNetworkRetries(maxNetworkRetries int) {
    s.Called(maxNetworkRetries) …
Run Code Online (Sandbox Code Playgroud)

go stripe-payments testify

5
推荐指数
1
解决办法
1737
查看次数

表驱动测试与 testify 模拟

是否有任何使用 testify 编写干净的表驱动测试的示例。输入和预期输出的表驱动测试效果很好,但必须测试依赖项的输出似乎真的很难做到。

下面的示例使用一个模拟接口,并要求我编写一个全新的测试函数来验证被测函数是否正确处理依赖项错误。我只是在寻找建议,使使用 testify 模拟包编写单元测试更加简化。

package packageone

import (
    "errors"
    "musings/packageone/mocks"
    "testing"
)
//Regular Table driven test
func TestTstruct_DoSomething(t *testing.T) {
    testObj := new(mocks.Dinterface)

    passes := []struct {
        Input  int
        Output int
    }{{0, 0}, {1, 1}, {2, 4}, {100, 10000}}

    for _, i := range passes {
        testObj.On("DoSomethingWithD", i.Input).Return(i.Output, nil)
    }

    type fields struct {
        DC Dinterface
    }
    type args struct {
        i int
    }
    tests := []struct {
        name    string
        fields  fields
        args    args
        wantRes int
        wantErr bool …
Run Code Online (Sandbox Code Playgroud)

testing mocking table-driven go testify

4
推荐指数
1
解决办法
2400
查看次数

Go 单元测试 - 调用数据库事务开始,出现意外错误

我正在尝试使用 Data Doggo-sqlmock和.Go 编写模型单元测试testify

我有以下代码:

type Suite struct {
    suite.Suite
    DB *gorm.DB
    mock sqlmock.Sqlmock

    repository      Repository
    user *models.User
}

func (s *Suite) SetupSuite() {
    var (
        db  *sql.DB
        err error
    )

    db, s.mock, err = sqlmock.New()
    require.NoError(s.T(), err)

    s.DB, err = gorm.Open("mysql", db)
    require.NoError(s.T(), err)

    s.DB.LogMode(true)

    s.repository = CreateRepository(s.DB)
}

func (s *Suite) AfterTest(_, _ string) {
    require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
    suite.Run(t, new(Suite))
}

func (s *Suite) Test_repository_Get() {
    var (
        ID        = …
Run Code Online (Sandbox Code Playgroud)

go testify go-gorm go-sqlmock

4
推荐指数
1
解决办法
2万
查看次数

InDelta和InEpsilon之间的区别

从文档:

https://godoc.org/github.com/stretchr/testify/assert#InDelta

InDelta断言这两个数字彼此相差不大

https://godoc.org/github.com/stretchr/testify/assert#InEpsilon

InEpsilon断言预期和实际的相对误差小于epsilon

他们的代码在目的上似乎是相同的:

func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {

    af, aok := toFloat(expected)
    bf, bok := toFloat(actual)

    if !aok || !bok {
        return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
    }

    if math.IsNaN(af) {
        return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
    }

    if math.IsNaN(bf) {
        return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
    }

    dt := af - bf
    if dt < -delta || dt > …
Run Code Online (Sandbox Code Playgroud)

go testify

3
推荐指数
1
解决办法
360
查看次数

golang测试错误:在以下任何位置都找不到软件包“ github.com/stretchr/testify/assert”:

我的导入如下所示:

import (
"testing"

"github.com/stretchr/testify/assert"
)
Run Code Online (Sandbox Code Playgroud)

当我尝试运行“ go test”时,出现错误消息:

cannot find package "github.com/stretchr/testify/assert" in any of:
/Users/[username]/go/src/github.com/[group_name]/[project_name]/vendor/github.com/stretchr/testify/assert (vendor tree)
/usr/local/go/src/github.com/stretchr/testify/assert (from $GOROOT)
/Users/[username]/go/src/github.com/stretchr/testify/assert (from $GOPATH)
FAIL    github.com/[group_name]/[project_name]/lib/briteverify [setup failed]
Run Code Online (Sandbox Code Playgroud)

因此,似乎最后一行是问题所在,它在... / lib / briteverify中表示找不到github.com/stretchr/testify/assert。但是,我将此作为导入文件,所以不知道为什么会引发此错误。有什么想法吗?

go testify

2
推荐指数
1
解决办法
2534
查看次数

初始化循环Golang

您好,我正在尝试使我的功能单元可测试。其中一项建议是将函数分配给一个变量并使其全局可访问。我刚刚这样做了,但现在我遇到了初始化循环,下面是我的代码

////////////////////////
// main.go
////////////////////////

func DownloadFile(filename string) {
    // Initialized request variable here
    // ... doing initialization
    // End of initialization

    res = ProcessDownload(request)

    if res == 401 {
       return doRetry(filename)
    }

    // some code here
    return downloadFile(filename)
}

func DoRetry(filename string) {
    // Doing some database insert/updating
   return downloadFile(string)
}
Run Code Online (Sandbox Code Playgroud)

在我的另一个文件中,我将此函数分配给变量

//////////////////////
// global.go
//////////////////////

var downloadFile = DownloadFile
var doRetry = DoRetry
Run Code Online (Sandbox Code Playgroud)

我在 global.go 中这样做的原因是为了使DoRetryDownloadFile单元可测试。这意味着使用这种方法我可以模拟该函数而无需创建接口。因为这只是一个独立的函数,不需要位于某个类中。变量的所有其余部分都可以,但是当涉及执行递归行为的函数时,我收到以下错误

./global.go:22:5: initialization loop:
/go/src/project/global.go:22:5 downloadFile refers …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking go testify

2
推荐指数
1
解决办法
3086
查看次数

如何接收 testify 框架“assert”方法中的方法返回的多个值作为参数?

下面是一个返回多个值的示例代码。

func (c Calc) CreateTenantHandler(item *models.TenantInput) (*models.Response, *models.ErrorDetails) {

        ...
        ...
        ...

        return &models.Response{ResponseStatus: 201, TenantOutput: tenantoutput,}, nil

    }
Run Code Online (Sandbox Code Playgroud)

在测试文件中,我尝试做以下事情。

assert.Equal(t,[nil,nil],testObject.CreateTenantHandler(nil) );
Run Code Online (Sandbox Code Playgroud)

我还检查了其他答案,但找不到我需要的东西。

go testify

2
推荐指数
1
解决办法
3876
查看次数

使用 testify 模拟接口方法两次,输入和输出不同

如何在 golang 测试中模拟接口方法两次?例如:

type myCache interface{
    Get(key string, data interface{}) error
}

type service struct {
    cache myCache
}

func (s service) GetBookDetail() (BookDetail, error) {
    ...
    book := Book{}
    err := s.cache.Get("book", &book)
    if err != nil {
        return BookDetail{}, err
    }
    ...
    author := Author{}
    err := s.cache.Get("author", &author)
    if err != nil {
        return BookDetail{}, err
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

当我测试时func GetBookDetail(),我怎样才能模拟Get(key string, data interface{}) error两次?我尝试这样做但失败了:

func TestGetBookDetail(t *testing.T) {
    ...

    mockCache.On("Get",
        mock.MatchedBy(func(key string) …
Run Code Online (Sandbox Code Playgroud)

unit-testing go testify

2
推荐指数
1
解决办法
8289
查看次数

去assert.Equal一些带有time.Time对象的接口

我正在尝试检查返回的数据是否等于期望

这是我的功能:

func extractData(payload string) (interface{}, time.Time, error) {

    eventTime := gjson.Get(payload, "data.eventDateTime").String()

    dateTime, err := time.Parse("2006-01-02T15:04:05-07:00", eventTime)
    if err != nil {
        return nil, time.Time{}, fmt.Errorf("Date Time Error: %w", err)
    }

    body := data.Body{
        EventTime: dateTime,
    }

    return body, dateTime, nil
}
Run Code Online (Sandbox Code Playgroud)

这是我为其编写的单元测试:

func TestExtractData(t *testing.T) {

    tests := []struct {
        Name           string
        Payload        string
        ExpectedOutput interface{}
    }{
        {
            Name:    "test-2",
            Payload: "{\"data\":\"2020-11-02T10:44:48+01:00\"}",
            ExpectedOutput: data.Body{
                EventTime: time.Date(2020, 11, 2, 10, 44, 48, 0, time.FixedZone("CET", 3600)),
            },
        },
    }

    for …
Run Code Online (Sandbox Code Playgroud)

unit-testing go testify go-testing

2
推荐指数
1
解决办法
1万
查看次数