サーチ…


構文

  • unittest {...} - "unittesting"モードでのみ実行されるブロック
  • assert(<ブール値に評価される式>、<オプションのエラーメッセージ>)

ユニットテストブロック

テストは、バグのない安定したアプリケーションを保証する優れた方法です。インタラクティブなドキュメンテーションとして機能し、機能を壊す恐れなしにコードを修正することができます。 Dは、D言語の一部としてunittestブロック用の便利でネイティブな構文を提供します。 Dモジュールのどこでもunittestブロックを使用して、ソースコードの機能をテストすることができます。

/**
Yields the sign of a number.
Params:
    n = number which should be used to check the sign
Returns:
    1 for positive n, -1 for negative and 0 for 0.
*/
T sgn(T)(T n)
{
    if (n == 0)
        return 0;
    return (n > 0) ? 1 : -1;
}

// this block will only be executed with -unittest
// it will be removed from the executable otherwise
unittest
{
    // go ahead and make assumptions about your function
    assert(sgn(10)  ==  1);
    assert(sgn(1)   ==  1);
    assert(sgn(-1)  == -1);
    assert(sgn(-10) == -1);
}

unittestの実行

-unittestフラグをDコンパイラに渡すと、すべてのunittestブロックが実行されます。多くの場合、スタブされたmain関数をコンパイラに生成させるのが便利です。コンパイル&実行ラッパーrdmdを使用して、Dプログラムをテストするのは簡単です:

rdmd -main -unittest yourcode.d

もちろん、このプロセスを2つのステップに分割することもできます。

dmd -main -unittest yourcode.d
./yourcode

dubプロジェクトでは、すべてのファイルをコンパイルしてunittestブロックを実行すると便利です。

dub test

プロのヒント:チッピングを保存するためにシェルエイリアスとして `tdmd`を定義してください。
alias tdmd="rdmd -main -unittest"

あなたのファイルをテストするには:

tdmd yourcode.d

注釈付きユニットテスト

テンプレート化されたコードでは、関数の属性( @nogcが正しく推測されているかどうか)を確認することが有効です。特定のテストでこれを確実にするために、 @nogc全体をアノテートすることができます

@safe @nogc pure nothrow unittest
{
    import std.math;
    assert(exp(0)  ==  1);
    assert(log(1)  ==  0);
}

もちろん、Dの各ブロックには属性を注釈することができ、コンパイラはそれらが正しいことを確認します。たとえば、次の例は上記の例に似ています:

unittest
{
    import std.math;
    @safe {
        assert(exp(0)  ==  1);
        assert(log(1)  ==  0);
    }
}


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow