测试时,模拟新对象还是实例化新对象更好?
When testing, is it better to Mock or to Instantiate new objects?
当我想出以下问题时,我正在为我的应用程序编写一些单元测试:
模拟一个对象还是创建它的新实例哪个更好?
我问的是 POJO 对象,而不是具有实际逻辑的对象。
谢谢
What's better, to mock an object or to create a new instance of it?
有什么更好的?使用对象的实际 行为,还是您在测试中配置的对象行为?
希望很明显,实际行为更好。否则你可能只是在测试测试的实现,这没有任何用处。
事实上,在最坏的情况下,您可以配置您的 mock 来执行在生产代码中根本不可能发生的事情。例如,Mockito 中曾经有一个错误,允许您指定 mock 应该抛出该方法不允许抛出的已检查异常。
关于模拟的Wikipedia article描述了适合使用模拟的情况:
If an object has any of the following characteristics, it may be
useful to use a mock object in its place:
- the object supplies non-deterministic results (e.g. the current time or the current temperature);
- it has states that are difficult to create or reproduce (e.g. a network error);
- it is slow (e.g. a complete database, which would have to be initialized before the test);
- it does not yet exist or may change behavior;
- it would have to include information and methods exclusively for testing purposes (and not for its actual task).
因此,在特定情况下,mock 有其用处;但您应该始终支持在可行的情况下使用 actual 实现。
当我想出以下问题时,我正在为我的应用程序编写一些单元测试:
模拟一个对象还是创建它的新实例哪个更好?
我问的是 POJO 对象,而不是具有实际逻辑的对象。
谢谢
What's better, to mock an object or to create a new instance of it?
有什么更好的?使用对象的实际 行为,还是您在测试中配置的对象行为?
希望很明显,实际行为更好。否则你可能只是在测试测试的实现,这没有任何用处。
事实上,在最坏的情况下,您可以配置您的 mock 来执行在生产代码中根本不可能发生的事情。例如,Mockito 中曾经有一个错误,允许您指定 mock 应该抛出该方法不允许抛出的已检查异常。
关于模拟的Wikipedia article描述了适合使用模拟的情况:
If an object has any of the following characteristics, it may be useful to use a mock object in its place:
- the object supplies non-deterministic results (e.g. the current time or the current temperature);
- it has states that are difficult to create or reproduce (e.g. a network error);
- it is slow (e.g. a complete database, which would have to be initialized before the test);
- it does not yet exist or may change behavior;
- it would have to include information and methods exclusively for testing purposes (and not for its actual task).
因此,在特定情况下,mock 有其用处;但您应该始终支持在可行的情况下使用 actual 实现。