工具分享:JsMockito (JavaScript 单元测试工具)

JsMockito

    用过Rhino Mocks后大家一定对它印象深刻,用它来做单元测试的case相当的省事。今天咱们同样来介绍一款Mock工具:JsMockito,用它能轻松的制作JavaScript程序的单元测试case。

    JsMockito的运行还依赖另外一款开源的JS工具:JsHamcrest,我们可以通过如下代码来搭建测试环境:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Test JavaScript Mock</title>
    <script src="jshamcrest.js" language="javascript" type="text/javascript"></script>
    <script src="jsmockito.js" language="javascript" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var mockFunc = JsMockito.mockFunction();
        JsMockito.when(mockFunc)('jim').thenReturn('hello jim');
        alert(mockFunc('jim'));
    </script>
</head>
<body>

</body>
</html>


模拟JS的原生对象

        var mockArray = JsMockito.mock(Array);
        JsMockito.when(mockArray).slice(10).thenReturn('^__^');
        alert(mockArray.slice(10));  //结果是: ^__^

 

模拟对象的方法

        bob = {
            FullName: 'bob ling',
            Introduce: function () { return 'im bob'; }
        };


        var mockIntroduce = JsMockito.mockFunction();
        JsMockito.when(mockIntroduce)().thenReturn("it's ok!");

        bob.Introduce = mockIntroduce;
        alert(bob.Introduce()); //结果是: it's ok

 

模拟对象的属性

        var mockBob = JsMockito.mock(bob);
        mockBob.FullName = 'Bruce Lee';
        alert(mockBob.FullName);//结果是:Bruce Lee


 

模拟对象的方法(根据输入参数的情况来返回结果)

        var mockFunction = JsMockito.mockFunction();
        JsMockito.when(mockFunction)(JsHamcrest.Matchers.lessThan(10) && JsHamcrest.Matchers.greaterThan(5), JsHamcrest.Matchers.anything()).thenReturn('this value must belong 5 to 10');
        alert(mockFunction(6, null)); //this value must belong 5 to 10
        alert(mockFunction(2, null));//undefined


 

模拟对象的方法(根据调用环境的不同来返回结果)

        context1 = {};
        context2 = {};
        var mockFunc = JsMockito.mockFunction();
        JsMockito.when(mockFunc).call(context1).thenReturn('this method was called by context');

        alert(mockFunc.apply(context1)); //this method was called by context
        alert(mockFunc.apply(context2)); //undefined

        alert(mockFunc.call(context1)); //this method was called by context
        alert(mockFunc.call(context2)); //undefined



 

你可能感兴趣的:(JavaScript,XHTML,单元测试,工具,单元测试工具)