嘲讽的目的 [英] The Purpose of Mocking

查看:11
本文介绍了嘲讽的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘲笑的目的是什么?

我一直在关注一些使用 NUnit 进行测试和 Moq 进行模拟的 ASP.NET MVC 教程.不过,我对其中的嘲弄部分有点不清楚.

I have been following some ASP.NET MVC tutorials that use NUnit for testing and Moq for mocking. I am a little unclear about the mocking part of it though.

推荐答案

模拟的目的是将被测试的类与其他类隔离.

这在上课时很有帮助:

  • 连接到外部资源(文件系统、数据库、网络...)
  • 设置成本高昂,或尚不可用(正在开发硬件)
  • 减慢单元测试的执行速度
  • 具有不确定的行为
  • 拥有(或现在是)用户界面

它还可以更容易地测试错误条件,因为您构建模拟对象以便它返回和错误,抛出异常......

It also makes it easier to test for error conditions, as your build your mock object so that it returns and error, throw an exception ...

mock 可以记录它是如何被调用的(函数调用顺序、参数),这可以通过测试来验证.例如:您正在测试的方法会发送一条消息,例如 IPC.mock对象的方法可以记录它被调用了多少次,他收到的参数(即要发送的消息).然后测试可以询问模拟对象并断言发送的消息数量,消息的内容......同样,模拟对象可以记录在日志字符串中调用的方法,测试可以检索该字符串并对其进行断言.

The mock can record how it was invoked (function calls order, parameters) and this can be verified by the test. For instance: The method you're testing sends a message, such as an IPC. The method of the mock object can record how many times it was invoked, the parameter he received (i.e. the message to be sent). Then the test can interrogate the mock object and assert on the number of messages sent, the content of the message ... Likewise, the mock object can record the methods that are called in a log string and the test can retrieve that string and assert on it.

不要滥用模拟对象:测试行为而不是实现,否则单元测试与代码的耦合过于紧密,并且脆弱(重构时中断).

Do not abuse of mock objects: test the behaviour rather than the implementation, or the unit tests will be too tightly coupled to the code, and brittle (break at refactoring).

Mock 可以手动编码,也可以由模拟框架生成.

Mock can be coded manually, or generated by a mocking framework.

这篇关于嘲讽的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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