tddjs > Ajax p258 スタブ

スタブのサンプル ■テストダブル テストに使う本物のように扱われるが実際には中身の薄いにせもののことの総称。 スタブ, テスト, フェイクなどがある。

by s_hiroshi

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css">
<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
  <h1 id="qunit-header">QUnit example</h1>  <h2 id="qunit-banner"></h2>  <div id="qunit-testrunner-toolbar"></div>  <h2 id="qunit-userAgent"></h2>  <ol id="qunit-tests"></ol>  <div id="qunit-fixture">test markup, will be hidden</div>

JavaScript

// スタブはあらかじめプログラミングされた振る舞いを持つテストダブルである。
// スタブは、引数がなんであっても同じ値を返したり、例外を投げたりする。
// スタブは実際のオブジェクト、関数の代わりに使われるので、テストに不要な
// テストに不要なインターフェースを使わずに済ませる方法としても使われる。

// stubFnの戻り値はfn関数(クロージャー)
// fnは呼び出されると
// 1. calledプロパティをture(実行済み)に変更。
// 2. argsプロパティにfnを呼び出した実引数を保持。
// 3. 包含関数(stubFn)の引数(自由変数)を返す
function stubFn(returnValue) {
    var fn = function() {
        fn.called = true;
        fn.args = arguments;
        return returnValue;
    };
    fn.called = false;
    return fn;
}

module('chapter12 Stub Function sample', {
    setup: function() {
        this.funcobj = stubFn({
            x: "10",
            y: "20"
        });
        this.obj = this.funcobj("a", "b");
    }
});
test('test should property that called of fn has is true', function() {
    ok(this.funcobj.called);
});

test('test should that args element equal arguments', function() {
    deepEqual(this.funcobj.args[1], "b");
});