英文:
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
你不能模拟一个库、模块或包,你只能模拟一个类型。
模拟任何类型的方法都是相同的:
- 创建一个包含你从该类型中使用的方法的接口。
- 将接受该类型的函数改为接受该接口。
- 创建一个满足测试需求的模拟类型,该类型满足接口的要求。
- 在生产代码中传递真实的类型,在测试代码中传递模拟类型。
英文:
You cannot mock a library or module or package, you can only mock a type.
Mocking any type works the same way:
- Create an interface that covers the methods you use from that type
- Change functions that take that type to take the interface instead
- Create a mock type that satisfies the interface for use in testing
- Pass the real type in production code, and the mock in test code
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论