Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes from Version 1 of UnittestsExample/D1

Show
Ignore:
Author:
Andrej08 (IP: 78.2.57.183)
Timestamp:
09/05/10 16:38:29 (14 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • UnittestsExample/D1

    v0 v1  
     1= Unittests = 
     2 
     3''Part of'' TutorialFundamentals 
     4 
     5== Description == 
     6 
     7Unittests let you find the bugs before you even run the program. 
     8 
     9 
     10== About unittests == 
     11 
     12According 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 
     14The -unittests flag has to be used to compile this program or else this code is ignored. 
     15         
     16 
     17== Example == 
     18 
     19{{{ 
     20#!d 
     21module unittests; 
     22 
     23import std.stdio; 
     24 
     25void 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 
     37class 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 
     50unittest { 
     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 
     67module unittests; 
     68 
     69import std.stdio; 
     70 
     71void main() { 
     72  writefln( "Passes!"); 
     73 
     74  return; 
     75} 
     76 
     77 
     78class 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}}}