dongxiaoguang9108 2018-08-02 20:40
浏览 88

具有Google Cloud API依赖项的单元测试代码

I'm writing a small slack bot which helps my developers get DB dumps from Google Cloud SQL. I've written it using https://godoc.org/cloud.google.com/go packages heavily, but now I've stumbled in writing unit tests. I want to opensource the code for others to use, but want to contribute something that follows basic guidelines, i.e. has test coverage.

I've read a lot about mocking, using interfaces, and that google library is notorious for being a pain to use in tests, and that Google people look down on mocking. But still can't make first step to writing tests, piece of code for example:

type StorageClient struct {
    client       *storage.Client
    targetBucket string
    Logger       *log.Logger
    context      context.Context
}
...
// Accepts name of object to be published, makes it world readable and returns its public URL as a string
func (c *StorageClient) PublishDumpFile(name string) (string, error) {
    obj := c.client.Bucket(c.targetBucket).Object(name)
    err := obj.ACL().Set(c.context, storage.AllUsers, storage.RoleReader)
    if err != nil {
        return "", err
    }
    return fmt.Sprintf("http://storage.googleapis.com/%s/%s", c.targetBucket, name), nil
}

Notice the cascading calls like Bucket().Object() and such, each returns new struct, so to mock it I'd need to define for each one a corresponding interface and create logic inside my test that will somewhat resemble logic behind google package (Bucket() returns struct which belongs to interface which has Object() method which returns... etc). But at this point I'm thinking I'm approaching it from wrong perspective.

I'm new to this ecosystem and testing such high-level things, so any help appreciated.

  • 写回答

1条回答 默认 最新

  • doudai3012 2018-08-22 15:34
    关注

    Unit tests should test functions without side effects, if you are testing a function that calls storage you're really running an integration test which if you're to test it properly needs to actually call the real service. Is it not possible to test against Google Cloud using a test bucket? Then there's no mocking required.

    To use the code you need GCS access, so to test it (with integration tests), you need access too. The alternative is really just testing a vast array of complex mocks which is too fragile and not really testing anything at all except your code + some code written solely with your code in mind.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊