我应该在生产代码中使用模拟吗? [英] Should I use mocking in production code?

查看:72
本文介绍了我应该在生产代码中使用模拟吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我需要模拟生产中的一些代码.这是为了使代码的一部分,以一半的功能工作.

I have a situation where I need to mock some code in production. This is for making one part of code, work in half functionality.

我必须选择编写一个空类(以实现接口),或使用像moq这样的模拟系统.

I have to choose to write an empty classes (to implement the interface) , or use a mocking system like moq.

问题是,模拟系统会达到性能,还是破坏生产代码的可读性?

So the question is, do the mocking systems hit the performance, or break some readability of the production code?

更新
例如:

update
example:

interface IRocketSystem
{
   void LaunchTheRocket();
}

class SimulationRocketSystem:IRocketSystem
{
...
}

class RocketSystem:IRocketSystem
{
...
}

我发现我在生产中有一个SimulationRocketSystem类,该类很小并且体内没有很多东西.模拟系统只有一行代码( new Mock< IRocketSystem>().Object )来替换这样的类.

i found that i have a SimulationRocketSystem classes in production, that small and don't have a lot in the body. the mock system is have one line of code ( new Mock < IRocketSystem >().Object ) to replace classes like this.

嘲讽的优点:
项目中的空类更少.

the pros for mocking:
less empty classes in project.

推荐答案

听起来像空对象.我不相信出于以下两个原因使用模拟框架.

Sounds like a Null Object. I don't believe in using mocking frameworks for this for two reasons.

首先,它会损害可读性.您可以使用适当命名的空类来实现接口,然后在该类中记录意图.另一方面,如果使用模拟框架,则文档需要嵌入到代码中的某个位置.此外,由于人们倾向于在测试代码中使用模拟,而又不了解您使用模拟的意图,这会造成混乱.

First, it hurts readability. You implementing the interface with an appropriately named empty class, then you document the intent inside that class. On the other hand, if you use a mocking framework, your documentation needs to be embedded in the code somewhere. Furthermore, it will be confusing as people tend to expect mocks in test code and not understand your intent for using mocks.

第二,您必须考虑如果有人修改了界面会发生什么.如果添加了方法怎么办?是否应该默认为返回null-像某些框架那样?如果方法必须根据接口协定返回某些特定的返回值,该怎么办?如果您有具体的实现,则编译器至少会在某种程度上保护您.如果您使用模拟框架,则可能会不走运.

Second, you have to consider what happens if someone modifies the interface. What if a method is added? Should it default to returning null - as some frameworks would do? What if the method must return some specific return value according to the interface contract. If you have a concrete implementation, then the compiler will at least protect you somewhat. If you use a mocking framework, you may be out of luck.

这篇关于我应该在生产代码中使用模拟吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆