要区分stub与mock在缺少编程实践经验的时候有些困难。
- mock的意思是模仿
- stub的意思是存根
不同的对比
模仿与简单替换
- Stub是代码的一部分。其目的就是用简单的行为替换复杂的行为,从而允许独立地测试代码的一部分。
- Mock Object是使用来代替与你的代码协作的对象的对象,这样代码可以调用Mock Object的方法,这些方法的调用的结果是由你的测试设置好的。
记录 验证预期
- Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations.
- Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behavior, state of the “fake”object in order to utilize a test scenario
中文大意
- Mock对象用于定义预期,即:在这种情况下,我期望方法A()能在带这样或那样的参数的调用。Mock记录并验证这样的期望。
-
Stub,在另一方面有不同的目的:他们并不记录或验证预期,而是允许我们在替换 fake对象的行为,以便利用测试一个测试场景。
-
A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.
- Tests written with mocks usually follow an initialize-> set expectations -> exercise > verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify. The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.
理解
stub
- Stub是一种状态确认
- Stub用简单的行为来替换复杂的行为
mock
- Mock是一种行为确认
- Mock模拟行为
stub && mock
- Stub从某种程度上来说,会返回我们一个特定的结果,用代码替换来方法。
- Mock确保这个方法被调用。
理解下的stub与mock
stub从字面意义上来说是存根,存根可以理解为我们保留了一些预留的结果。这个时候我们相当于构建了这样一个特殊的测试场景,用于替换诸如网络或者IO口调度等高度不可预期的测试。如当我们需要去验证某个api被调用并返回了一个结果,举例在最小物联网系统设计中返回的json,我们可以在本地构建一个[{"id":1,"temperature":14,"sensors1":15,"sensors2":12,"led1":1}]的结果来当我们预期的数据,也就是所谓的存根。那么我们所要做的也就是解析json,并返回预期的结果。当我们依赖于网络时,此时测试容易出现问题。
mock从字面意义上来说是模仿,也就是说我们要在本地构造一个模仿的环境,而我们只需要验证我们的方法被调用了。
或许您还需要下面的文章: