【问题标题】:How to test this simple method with Go?如何用 Go 测试这个简单的方法?
【发布时间】:2016-11-04 15:39:16
【问题描述】:

我正在编写一些单元测试,但我一直在为以下方法编写测试:

func (database *Database) FindUnusedKey() string {
    count := 0
    possibleKey := helpers.RandomString(helpers.Config.KeySize)
    for database.DoesKeyExist(possibleKey) {
        possibleKey = helpers.RandomString(helpers.Config.KeySize + uint8(count/10))
        count++
    }
    return possibleKey
}

我想要一个测试,其中 helpers.RandomString(int) 返回一个字符串,该字符串已经是我的数据库中的一个键,但我没有找到在我的测试中重新声明或修改 helpers.RandomString(int) 的方法。

我尝试使用 testify mock,但似乎不可能。

我做错了吗?

谢谢。

【问题讨论】:

  • 您没有提到您正在使用的数据库引擎,但大多数关系数据库确实有生成键的方法(序列、自动 inc 字段)。我建议使用这些而不是在客户端生成密钥。
  • 我自己没用过,不过好像有autoinc的key:github.com/boltdb/bolt#autoincrementing-integer-for-the-bucket

标签: testing go testify


【解决方案1】:

您可以通过依赖注入提取database.DoesKeyExist,并提供一个在单元测试中首次返回 true 的函数。更多详情http://openmymind.net/Dependency-Injection-In-Go/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2019-12-13
    • 2011-04-12
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多