简体   繁体   English

Python-为什么我们应该使用模拟进行测试?

[英]Python - Why we should use mock to do test?

I am very new to Python and I saw many projects on Github using Mock to do their test but I don't understand why. 我对Python非常陌生,我在Github上看到了许多使用Mock进行测试的项目,但我不明白为什么。
When we use mock, we construct a Mock object with a specific return_value, I don't truely understand why we do this. 当我们使用模拟时,我们使用特定的return_value构造了一个Mock对象,我不真正理解我们为什么这样做。 I know sometimes it is difficult to build our needed resources but what is the point if we construct a object/function with a certain return value ? 我知道有时很难构建所需的资源,但是如果我们构造具有特定返回值的对象/函数又有什么意义呢?

Mock can help to write unit tests. 模拟可以帮助编写单元测试。 In unit tests, you want to test a small portion of your implementation. 在单元测试中,您想测试实现的一小部分。 For example, as small as one function or one class. 例如,只有一个函数或一个类。

In a moderately large software, these small parts depend on each other. 在中等大小的软件中,这些小部分相互依赖。 Or sometimes there are external dependencies. 或有时存在外部依赖性。 You open files, do syscalls, or get external data in some other way. 您打开文件,执行系统调用或以其他方式获取外部数据。

While writing a directed unit test for a small portion of your code, you do not want to spend time to set-up everything else around it. 在为代码的一小部分编写定向单元测试时,您不想花费时间来设置代码周围的所有其他内容。 (The files, syscalls, external data). (文件,系统调用,外部数据)。 Mock comes to your help there. 模拟会在那里为您提供帮助。 With mock, you can make the other dependencies of your code behave exactly as you like. 借助模拟,您可以使代码的其他依赖项完全按照您的意愿运行。 This way you can focus on testing your intended implementation. 这样,您可以专注于测试预期的实现。

Coming to the mock with the return value: Say you want to test func_a . 使用返回值进入模拟:说您想测试func_a And func_a calls func_b . 并且func_a调用func_b func_b does a lot of funky processing to calculate its return value. func_b了大量时髦的处理以计算其返回值。 For example, talking to an external service, doing bunch of syscalls, or some other expensive operation. 例如,与外部服务通话,进行大量系统调用或其他昂贵的操作。 Since you are testing func_a , you only care about possible return values of func_b . 由于您正在测试func_a ,因此只关心func_b可能返回值。 (So that func_a can use them) In this scenario you would mock func_b and set the return values explicitly. (以便func_a可以使用它们)在这种情况下,您将模拟func_b并显式设置返回值。 This can really simplify your test complexity. 这确实可以简化您的测试复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM