MockMe:一个新的JavaScript mocking框架

Johannes Link是一个热爱Agile的小伙子,他对现存的JavaScript单元测试框架不100%满意,他解释了原因,比如他给出了一个例子:

Js代码 复制代码
  1. testDoubleSpeaker:function(){with(this){
  2. varactualMsg=null;
  3. varmockSay=function(msg){
  4. actualMsg=msg;
  5. };
  6. Speaker.say=mockSay;
  7. DoubleSpeaker.say('oops');
  8. assertEqual('oopsoops',actualMsg);
  9. }}
testDoubleSpeaker: function() { with(this) { var actualMsg = null; var mockSay = function(msg) { actualMsg = msg; }; Speaker.say = mockSay; DoubleSpeaker.say('oops'); assertEqual('oopsoops', actualMsg); }}

这个例子能够运行,但是下面的方式是不是更好?
Js代码 复制代码
  1. testDoubleSpeaker:function(){with(this){
  2. mock(Speaker).andDo(function(){
  3. DoubleSpeaker.say('oops');
  4. verify(Speaker.say)('oopsoops');
  5. });
  6. }},
testDoubleSpeaker: function() { with(this) { mock(Speaker).andDo(function() { DoubleSpeaker.say('oops'); verify(Speaker.say)('oopsoops'); }); }},


所以,他给出了一个新的JavaScript mocking框架: MockMe。主要功能是:

1。提供基本颗粒mocking的功能,如果可能,可以伪装一个简单测试功能,而不影响其他内容(比如对象,原型或者全局命名空间等)。

2。很多时候,spying(刺探)比mocking更好,因为前者更简单。spying指的不是在你的mock对象开始测试前,指定期望的特定反馈,而是当测试发生时或之后,你使用mock spy对象来刺探反馈结果。

下面是另外一个例子:

Js代码 复制代码
  1. when(f)('in').thenReturn('out');
  2. assertEqual('out',f('in'));
  3. when(f)({name:'hello'}).thenReturn('yeah');
  4. assertEqual('yeah',f({name:'hello'}));
  5. when(f)(any()).thenReturn('yeah');
  6. assertEqual('yeah',f(1));
  7. verify(times(2),f)(1);//succeeds
  8. useMockerFor(function(mocker)){
  9. mocker.within(MyObject).mock('f1');
  10. when(MyObject.f1)().thenReturn(5);
  11. assertEqual(7,MyObject.f2());
  12. }//Hereeverythingyoumockedwillautomaticallyberestored
  13. assertEqual(3,MyObject.f2());
when(f)('in').thenReturn('out'); assertEqual('out', f('in')); when(f)({name: 'hello'}).thenReturn('yeah'); assertEqual('yeah', f({name: 'hello'})); when(f)(any()).thenReturn('yeah'); assertEqual('yeah', f(1)); verify(times(2), f)(1); //succeeds useMockerFor(function(mocker)) { mocker.within(MyObject).mock('f1'); when(MyObject.f1)().thenReturn(5); assertEqual(7, MyObject.f2()); } // Here everything you mocked will automatically be restored assertEqual(3, MyObject.f2());

详细内容可以访问 http://johanneslink.net/projects/mockme.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值