如何在运行Cucumber时模拟服务/控制器内使用的库?

huangapple go评论64阅读模式
英文:

How to mock libraries used inside service/controller while running cucumber

问题

我正在使用黄瓜(Cucumber)来运行验收测试。
我正在使用以下Zendesk库来调用创建工单和查看工单的方法:
https://github.com/nukosuke/go-zendesk

我想知道在编写验收测试时如何模拟这个库。我正在使用依赖注入设计来在单元测试用例中进行测试。但是我不知道在验收测试中如何进行模拟。

我知道在验收测试中,你应该实际运行而不进行模拟,但是假设现在与这个Zendesk API相关的成本很高,我不想实际调用Zendesk API。

我应该如何在这里模拟这个库?

谢谢。

英文:

I am using cucumber to run acceptance tests.
I am using the following Zendesk library to call methods to create tickets, and view them
https://github.com/nukosuke/go-zendesk

I want to know while writing acceptance tests how to mock this library. I am using dependency injection design to test this on a unit test case. But I don't know how I can mock it while acceptance tests.

I know that in case of acceptance tests, you should actually run it without mocking, but let's say that there is cost associated with this zendesk api for now, and I don't want to actually call zendesk api behind the scenes.

How can i mock the library here?

Thanks

答案1

得分: 1

你不能模拟一个库、模块或包,你只能模拟一个类型。

模拟任何类型的方法都是相同的:

  1. 创建一个包含你从该类型中使用的方法的接口。
  2. 将接受该类型的函数改为接受该接口。
  3. 创建一个满足测试需求的模拟类型,该类型满足接口的要求。
  4. 在生产代码中传递真实的类型,在测试代码中传递模拟类型。
英文:

You cannot mock a library or module or package, you can only mock a type.

Mocking any type works the same way:

  1. Create an interface that covers the methods you use from that type
  2. Change functions that take that type to take the interface instead
  3. Create a mock type that satisfies the interface for use in testing
  4. Pass the real type in production code, and the mock in test code

huangapple
  • 本文由 发表于 2023年3月22日 21:47:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75813094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定