| 1 | = Unittests = |
---|
| 2 | |
---|
| 3 | ''Part of'' TutorialFundamentals |
---|
| 4 | |
---|
| 5 | == Description == |
---|
| 6 | |
---|
| 7 | Unittests let you find the bugs before you even run the program. |
---|
| 8 | |
---|
| 9 | |
---|
| 10 | == About unittests == |
---|
| 11 | |
---|
| 12 | According to this example, unittests may be run in the order they appear in the code. Since the Whatever class appears before the module unittests, these are run first. |
---|
| 13 | |
---|
| 14 | The -unittests flag has to be used to compile this program or else this code is ignored. |
---|
| 15 | |
---|
| 16 | |
---|
| 17 | == Example == |
---|
| 18 | |
---|
| 19 | {{{ |
---|
| 20 | #!d |
---|
| 21 | module unittests; |
---|
| 22 | |
---|
| 23 | import std.stdio; |
---|
| 24 | |
---|
| 25 | void main() { |
---|
| 26 | writefln("test"); |
---|
| 27 | /* This assertion will fail. */ |
---|
| 28 | assert(false); |
---|
| 29 | |
---|
| 30 | /* |
---|
| 31 | The line number (7) may be different, but this is the |
---|
| 32 | error message which should appear... |
---|
| 33 | Error: AssertError Failure unittests(7) |
---|
| 34 | */ |
---|
| 35 | } |
---|
| 36 | |
---|
| 37 | class Whatever { |
---|
| 38 | |
---|
| 39 | unittest { |
---|
| 40 | writefln("class Whatever UnitTest..."); |
---|
| 41 | /* If the expession of an assert doesn't evaluate to true, an exception is thrown at run-time. */ |
---|
| 42 | |
---|
| 43 | assert(true==1); |
---|
| 44 | assert(true); |
---|
| 45 | assert(false==false); |
---|
| 46 | assert(!false); |
---|
| 47 | } |
---|
| 48 | } |
---|
| 49 | |
---|
| 50 | unittest { |
---|
| 51 | writefln("module UnitTest..."); |
---|
| 52 | assert(true==1); |
---|
| 53 | assert(true); |
---|
| 54 | assert(false==false); |
---|
| 55 | } |
---|
| 56 | }}} |
---|
| 57 | |
---|
| 58 | |
---|
| 59 | |
---|
| 60 | |
---|
| 61 | |
---|
| 62 | |
---|
| 63 | == Example 2 == |
---|
| 64 | |
---|
| 65 | {{{ |
---|
| 66 | #!d |
---|
| 67 | module unittests; |
---|
| 68 | |
---|
| 69 | import std.stdio; |
---|
| 70 | |
---|
| 71 | void main() { |
---|
| 72 | writefln( "Passes!"); |
---|
| 73 | |
---|
| 74 | return; |
---|
| 75 | } |
---|
| 76 | |
---|
| 77 | |
---|
| 78 | class Factoid { |
---|
| 79 | int factorial() { |
---|
| 80 | int x = 1; |
---|
| 81 | int f; |
---|
| 82 | |
---|
| 83 | for( x = 0 ; x <= m_int; ++x) { |
---|
| 84 | if( x == 0) { |
---|
| 85 | f = 1; |
---|
| 86 | } |
---|
| 87 | else { |
---|
| 88 | f *= x; |
---|
| 89 | } |
---|
| 90 | } |
---|
| 91 | |
---|
| 92 | return f; |
---|
| 93 | } |
---|
| 94 | |
---|
| 95 | |
---|
| 96 | this(int x) { |
---|
| 97 | m_int = x; |
---|
| 98 | } |
---|
| 99 | |
---|
| 100 | private{ |
---|
| 101 | int m_int; |
---|
| 102 | } |
---|
| 103 | |
---|
| 104 | unittest{ |
---|
| 105 | Factoid f = new Factoid(3); |
---|
| 106 | |
---|
| 107 | assert( 6 == f.factorial()); |
---|
| 108 | } |
---|
| 109 | } |
---|
| 110 | }}} |