Stub桩
为什么叫桩,我不知道。
更多的是一种测试概念,test stub
来看看Martin的说明吧:
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test.
一个对象中封装了测试当中会调用的方法,并且相应输出一些测试结果。但这只是针对测试调用和响应,并不会实现所有的方法。那么这个对象就被称为stub.
顺道说说Mock(并不是重点)
这里主要说的是stub,mock并不是重点。
测试的重点就是:输入,模拟依赖输出,验证输出结果。
在测试之前,stub为了测试需要,将需要的answers已经封装到一个对象中。
例子如下:
public interface MailService {public void send (Message msg);
}
public class MailServiceStub implements MailService {private List<Message> messages = new ArrayList<Message>();public void send (Message msg) {messages.add(msg);}public int numberSent() {return messages.size();}
} class OrderStateTester...public void testOrderSendsMailIfUnfilled() {Order order = new Order(TALISKER, 51);MailServiceStub mailer = new MailServiceStub();order.setMailer(mailer);order.fill(warehouse);assertEquals(1, mailer.numberSent());}
mock,则不会去封装实现一个对象,而是借助mock工具来模拟依赖输出an
例子如下:
class OrderInteractionTester...public void testOrderSendsMailIfUnfilled() {Order order = new Order(TALISKER, 51);Mock warehouse = mock(Warehouse.class);Mock mailer = mock(MailService.class);order.setMailer((MailService) mailer.proxy());mailer.expects(once()).method("send");warehouse.expects(once()).method("hasInventory").withAnyArguments().will(returnValue(false));order.fill((Warehouse) warehouse.proxy());}
}
最终,他们两个都是为了在测试order的时候解决mailer依赖的问题。stub和mock的区别一目了然。
再来看看定义
这是维基中对stub的定义:
A method stub or simply stub in software development is a piece of code used to stand in for some other programming functionality. A stub may simulate the behavior of existing code (such as a procedure on a remote machine) or be a temporary substitute for yet-to-be-developed code.
Stub有两种意义:
* 模拟已有功能代码的表现
,只是外在表现而已哦。test stub正属于此。
* 还未开发完的代码的临时替身
。AIDL自动生成的Stub类属于此,这样命名在提醒实现者这里还有待实现的方法。