<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1084762708281241901</id><updated>2012-02-08T22:09:50.227+01:00</updated><category term='C#'/><category term='log4j'/><category term='xUnit'/><category term='Test Pattern'/><category term='TDD'/><category term='software'/><category term='books'/><category term='Code Contracts'/><category term='CruiseControl'/><category term='Mocks; Arrange Act Assert Syntax'/><category term='RhinoMocks'/><category term='NRefactory'/><category term='AAA Syntax'/><category term='Design by Contract'/><category term='codeproject'/><title type='text'>while(coding){DoTDD();}</title><subtitle type='html'>Notes about Software Engineering, Test-Driven Development, C#.NET, Java and ...</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>19</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-7732267395409794036</id><published>2011-12-21T16:52:00.022+01:00</published><updated>2012-01-17T21:03:16.083+01:00</updated><title type='text'>Testing Java Console Applications</title><content type='html'>Currently I'm reading the great book "Growing Object-Oriented Software, Guided by Tests" by Steve Freeman and Nat Pryce. They encourage us to drive software development in the large with an outer loop of end-to-end acceptance tests and in the small with an inner loop of unit tests. While implementing just for fun the &lt;a href="http://en.wikipedia.org/wiki/Nine_Men%27s_Morris"&gt;Nine Men's Morris&lt;/a&gt; board game with a simple console user interface, I tried to get a feeling for "test guided growing of software" as it is described in the book.
&lt;p/&gt;
During that exercise I needed to find a solution to control the input towards and the output from the console. The following example source code shows one possible solution.
&lt;p/&gt;
I started with an acceptance test. I choose to implement it with JUnit, but &lt;a href="http://fitnesse.org/"&gt;Fitnesse&lt;/a&gt; tool would have been an alternative.

&lt;pre class="brush:java"&gt;
public class NineMensMorrisAcceptanceTests {

  private ApplicationRunner application = new ApplicationRunner();
  
  @Test
  public void applicationAsksForUserMoveAndThenMakesOwnMove()
  {
    application.startGame();
    application.hasDisplayed("Nine Men's Morris");
    application.hasDisplayed("Please enter spot to place piece:");
    application.userEnters("1\r\n");
    application.hasDisplayed("Computer places piece on spot: 2");
  }
}
&lt;/pre&gt;

The ApplicationRunner class starts the console application in a new thread and acquires control over the input and output streams. Luckily Java has such a well designed IO system, which allows easy test set up. The game application writes to the console via &lt;em&gt;System.out&lt;/em&gt; and reads from the console via &lt;em&gt;System.in&lt;/em&gt;:    

&lt;pre class="brush:java"&gt;
public class ApplicationRunner {

  private PipedOutputStream pipedOutputStream;
  private PipedInputStream pipedInputStream;
  private ByteArrayOutputStream outputStream;

  public ApplicationRunner(){
    pipedOutputStream = new PipedOutputStream();
    pipedInputStream = new PipedInputStream(pipedOutputStream);
    System.setIn(pipedInputStream);

    outputStream = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outputStream));
  }
 
  public void startGame() {
    Thread thread = new Thread("Test Application"){
      @Override public void run(){Console.main(null);}
    };
    thread.setDaemon(true);
    thread.start();
  }

  public void hasDisplayed(String text) {
    boolean displayed = false; int tries = 20;
    while(tries&gt;0 &amp;&amp; !displayed){
      Thread.sleep(100);
      displayed = outputStream.toString().contains(text) ? true : false;
      tries--;
    }
    if (!displayed){
      throw new AssertionError("Missing text in output: " + text);
    }
  }

  public void userEnters(String userInput) {
    pipedOutputStream.write(userInput.getBytes());
  }
}
&lt;/pre&gt;

The &lt;em&gt;Console.main()&lt;/em&gt; method set ups and starts the console application:

&lt;pre class="brush:java"&gt;
public static void main(String[] args) {
  ConsoleGameUI consoleGameUI = new ConsoleGameUI();
  GameController controller = new GameController(
    consoleGameUI, 
    new Engine(),
    new MoveGenerator());
  consoleGameUI.init(new InputParser(),controller);
  controller.start();
}
&lt;/pre&gt;

When we develop the &lt;em&gt;ConsoleGameUI&lt;/em&gt; class, we will write some unit tests. There we can use also the hijacked streams to control inputs and outputs. Because this time the test runs synchronously we can use a ByteArrayInputStream instead of PipedInputStream to supply the user input to the system under test: 

&lt;pre class="brush:java"&gt;
public class ConsoleGameUITests {
 
  // Class under test
  ConsoleGameUI consoleGameUI;

  private String userInput;
  private ByteArrayInputStream inputStream;
  private ByteArrayOutputStream outputStream;
  ...
 
  @Before public void setUp() {
    userInput = "some input from user";
    inputStream = new ByteArrayInputStream(userInput.getBytes());
    outputStream = new ByteArrayOutputStream();
    System.setIn(inputStream);
    System.setOut(new PrintStream(outputStream));
    ... 
    consoleGameUI = new ConsoleGameUI();
    consoleGameUI.init(inputParserMock, gameControllerMock);
  }
 
  @Test public void shouldPromptTheUserToEnterSpotToPlaceAPiece(){
    consoleGameUI.askUserForMove(Turn.PLACE_WHITE);
    assertTrue(outputStream.toString().contains("Please enter spot to place piece:"));
  }

  @Test public void shouldPromptTheUserToEnterSpotsToSlidePiece(){
    consoleGameUI.askUserForMove(Turn.SLIDE_WHITE);
    assertTrue(outputStream.toString().contains("Please enter spots to slide piece:"));
  }

  @Test public void shouldReadInputAndCallParser()
  {
    context.checking(new Expectations() {{
      oneOf(inputParserMock).Parse(userInput);
      ...  
    }});
    consoleGameUI.askUserForMove(Turn.PLACE_WHITE);
    context.assertIsSatisfied();
  }
  ...
}
&lt;/pre&gt;

In the &lt;em&gt;ConsoleGameUI&lt;/em&gt; class we use &lt;em&gt;System.out&lt;/em&gt; and &lt;em&gt;System.in&lt;/em&gt;:

&lt;pre class="brush:java"&gt;
public class ConsoleGameUI implements GameUI {

  private final Scanner scanner;
  private IInputParser parser;
  private IGameController gameController;
 
  public ConsoleGameUI(){
    this.scanner = new Scanner(System.in);
  }
 
  public void init(IInputParser parser, IGameController gameController){...}
 
  @Override
  public MoveRequest askUserForMove(Turn turn) {
    switch(turn){
    case PLACE_WHITE:
      System.out.print("Please enter spot to place piece:"); 
      break;
    case SLIDE_WHITE:
      System.out.print("Please enter spots to slide piece:");
      break;
    ...  
    String line = scanner.nextLine();
    MoveRequest request = parser.Parse(line);
    return request;
  }
  ...
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-7732267395409794036?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/7732267395409794036/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=7732267395409794036' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/7732267395409794036'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/7732267395409794036'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2011/12/testing-java-console-applications.html' title='Testing Java Console Applications'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-6167345489429554684</id><published>2011-02-25T17:04:00.016+01:00</published><updated>2012-01-17T20:28:15.971+01:00</updated><title type='text'>Rhino Mocks Arrange / Act / Assert (AAA) Syntax Quick Reference</title><content type='html'>Recently I held a training session about Test-Driven Development(TDD) for .NET developers. A important part in this training was about Mocking, which is essential when you apply TDD to the real world. I presented several examples with Rhino Mocks and used the brilliant AAA syntax of Rhino Mocks. As supporting material for the practical exercises of the participants I missed a quick reference for this syntax style. Based on Ayende's article &lt;a href="http://www.ayende.com/wiki/Rhino+Mocks+3.5.ashx"&gt;Rhino Mocks 3.5&lt;/a&gt; and the &lt;a href="http://www.ayende.com/wiki/GetFile.aspx?File=Rhino+Mocks+3.3+Quick+Reference.pdf"&gt;Rhino Mocks 3.3 Quick Reference&lt;/a&gt; I created a new document with code examples:
&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;
&lt;a style="margin: 12px auto 6px; font: 14px Helvetica,Arial,Sans-serif; display: block; text-decoration: underline;" href="https://docs.google.com/viewer?a=v&amp;pid=explorer&amp;chrome=true&amp;srcid=0By6Nqi32xrTtMGQxMzc1MWItOTU5Yy00YmMzLTlhNjgtYWIxZmE4ZTUzZWI2&amp;hl=en_US"&gt;Rhino Mocks AAA Syntax Quick Reference on Google Docs&lt;/a&gt;
&lt;a title="View Rhino Mocks AAA Syntax Quick Reference on Scribd" href="http://www.scribd.com/doc/49587062/RhinoMocksAAAQuickReference" style="margin: 12px auto 6px; font: 14px Helvetica,Arial,Sans-serif; display: block; text-decoration: underline;"&gt;Rhino Mocks AAA Syntax Quick Reference on Scribd&lt;/a&gt; &lt;object id="doc_635178337297290" name="doc_635178337297290" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline: medium none;" height="600" width="100%"&gt;  &lt;param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"&gt;  &lt;param name="wmode" value="opaque"&gt;   &lt;param name="bgcolor" value="#ffffff"&gt;   &lt;param name="allowFullScreen" value="true"&gt;   &lt;param name="allowScriptAccess" value="always"&gt;   &lt;param name="FlashVars" value="document_id=49587062&amp;amp;access_key=key-1s0hguy3hybq5jpxhu73&amp;amp;page=1&amp;amp;viewMode=list"&gt;   &lt;embed id="doc_635178337297290" name="doc_635178337297290" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=49587062&amp;amp;access_key=key-1s0hguy3hybq5jpxhu73&amp;amp;page=1&amp;amp;viewMode=list" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" bgcolor="#ffffff" height="600" width="100%"&gt;&lt;/embed&gt;  &lt;/object&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-6167345489429554684?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/6167345489429554684/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=6167345489429554684' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/6167345489429554684'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/6167345489429554684'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2011/02/rhino-mocks-arange-act-assert-aaa.html' title='Rhino Mocks Arrange / Act / Assert (AAA) Syntax Quick Reference'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-5009908349070830489</id><published>2010-11-04T13:59:00.006+01:00</published><updated>2010-11-04T14:25:47.766+01:00</updated><title type='text'>'Design By Contract' Metrics</title><content type='html'>We are currently introducing 'Design By Contract' to a software development group of about 60 developers, which are developing different components. We started by defining 'Design By Contract' policies for C# and Java. It is quite challenging to manage this change effort. 
&lt;p&gt;&lt;/p&gt;
One piece of the change strategy is to measure the progress. We are counting the number of classes and the number of contract assertions (Preconditions, post conditions and invariants). So we have two statistics:

&lt;ol&gt;&lt;li&gt;   Absolut number of contract assertions per component&lt;/li&gt;&lt;li&gt;   Average number of contract assertions per class per component&lt;/li&gt;&lt;/ol&gt;
The metrics tell us whether contracts are "at all" be used. We want to increase the code quality with contracts. If we see a team not implementing any contracts or only very few, we can support the team with training and consulting.
&lt;p&gt;&lt;/p&gt;
The metrics are published on a regular basis and serve as a means for motivation.
&lt;p&gt;&lt;/p&gt;
The limitation of thise metrics is, that they do not tell whether a component has enough contracts, so its understandability, maintainability and so on is best supported with 'Design By Contract'. Quality of contracts is not covered by the metrics.
&lt;p&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-5009908349070830489?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/5009908349070830489/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=5009908349070830489' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5009908349070830489'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5009908349070830489'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2010/11/design-by-contract-metrics.html' title='&apos;Design By Contract&apos; Metrics'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-1640292166543291476</id><published>2010-10-28T23:04:00.010+02:00</published><updated>2010-11-04T13:15:15.801+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NRefactory'/><category scheme='http://www.blogger.com/atom/ns#' term='Code Contracts'/><category scheme='http://www.blogger.com/atom/ns#' term='Design by Contract'/><title type='text'>Example for parsing C# code with the NRefactory library</title><content type='html'>NRefactory is part of the open source IDE &lt;a href="http://www.icsharpcode.net/opensource/sd/"&gt;SharpDevelop&lt;/a&gt; for the .NET platform. NRefactory is a parser library for C# and VB. It can create an Abstract Syntax Tree (AST) that represents all constructs that are available in C# or VB. This AST can be used to analyze source code or to modify and generate code again.
&lt;/p&gt;
You can download the SharpDevelop IDE, install it and then find the ICSharpCode.NRefactory.dll in the bin folder of the installation. Or you download the SharpDevelop source code and compile the dll yourself.
&lt;/p&gt;
The example below shows how to parse C# source code files, generate an AST and then using the AST to create metrics about the number of classes and the number of &lt;a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Code Contracts&lt;/a&gt;.

&lt;pre class="brush:csharp"&gt;
using System;
using System.IO;
using System.Diagnostics.Contracts;
using ICSharpCode.NRefactory;
namespace ContractCounter
{
  class Program
  {
    public static void Main(string[] args)
    {
      TextReader reader = File.OpenText("Program.cs");
      using (IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, reader))
      {
        parser.Parse();
        if (parser.Errors.Count &amp;lt;= 0)
        {
          // Here we will use the parser.CompilationUnit(AST)
          ...
        }
        else
        {
          Console.WriteLine("Parse error: " + parser.Errors.ErrorOutput);
        }
      }
      Console.Write("Press any key to continue . . . ");
      Console.ReadKey(true);
    }
  }
}
&lt;/pre&gt;

To traverse the AST we can use the &lt;span style="font-style:italic;"&gt;Visitor&lt;/span&gt; pattern (see &lt;a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201633612"&gt;[Gamma et.al:Design Patterns]&lt;/a&gt;. We implement a new visitor 'CounterVisitor' for our purposes. We can inherit from the predefined 'AbstractAstVisitor'. In NRefactory visitors are responsible for traversing the AST by themselfs so we have to call the children when we are visiting certain node types:  

&lt;pre class="brush:csharp"&gt;
using System.Diagnostics.Contracts;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.Visitors;
namespace ContractCounter
{
  public class CounterVisitor : AbstractAstVisitor
  {
    public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
    {
      Contract.Requires(compilationUnit != null);
      
      // Visit children (E.g. TypeDcelarion objects)
      compilationUnit.AcceptChildren(this, data);
      
      return null;
    }

    public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
    {
      Contract.Requires(typeDeclaration != null);
      
      // Is this a class but not a test fixture?
      if (IsClass(typeDeclaration) &amp;&amp; !HasTestFixtureAttribute(typeDeclaration))
      {
        classCount++;
      }

      // Visit children (E.g. MethodDeclarion objects)
      typeDeclaration.AcceptChildren(this, data);
      
      return null;
    }

    public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
    {
      Contract.Requires(methodDeclaration != null);

      // Visit the body block statement of method declaration
      methodDeclaration.Body.AcceptVisitor(this, null);

      return null;
    }

    public override object VisitBlockStatement(BlockStatement blockStatement, object data)
    {
      Contract.Requires(blockStatement != null);

      // Visit children of block statement (E.g. several ExpressionStatement objects)
      blockStatement.AcceptChildren(this, data);

      return null;
    }

    public override object VisitExpressionStatement(ExpressionStatement expressionStatement, object data)
    {
      Contract.Requires(expressionStatement != null);

      // Visit the expression of the expression statement (E.g InnvocationExpression)
      expressionStatement.Expression.AcceptVisitor(this, null);

      return null;
    }

    public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
    {
      Contract.Requires(invocationExpression != null);

      // Visit the target object of the invocation expression (E.g MemberReferenceExpression)
      invocationExpression.TargetObject.AcceptVisitor(this, null);
      return null;
    }

    public override object VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, object data)
    {
      Contract.Requires(memberReferenceExpression != null);

      IdentifierExpression identifierExpression = memberReferenceExpression.TargetObject as IdentifierExpression;

      // Is this a call to Contract.Requires(), Contract.Ensures() or Contract.Invariant()?
      if ( identifierExpression != null &amp;&amp;
          identifierExpression.Identifier == "Contract" &amp;&amp;
          (memberReferenceExpression.MemberName == "Requires" ||
           memberReferenceExpression.MemberName == "Ensures" ||
           memberReferenceExpression.MemberName == "Invariant") )
      {
        assertionCount++;
      }

      return null;
    }

    public int ClassCount {
      get { return classCount; }
    }

    public int AssertionCount
    {
      get { return assertionCount; }
    }

    #region private members
    private int classCount;
    private int assertionCount;

    static private bool IsClass(TypeDeclaration typeDeclaration)
    {
      return typeDeclaration.Type == ClassType.Class;
    }

    static private bool HasTestFixtureAttribute(TypeDeclaration typeDeclaration)
    {
      bool hasTestFixtureAttribute = false;
      foreach (AttributeSection section in typeDeclaration.Attributes) {
        foreach (Attribute attribute in section.Attributes) {
          if (attribute.Name == "TestFixture") {
            hasTestFixtureAttribute = true;
            break;
          }
        }
      }
      return hasTestFixtureAttribute;
    }
    #endregion
  }
}
&lt;/pre&gt;

The actual counting takes place in the VisitTypeDeclaration() and the VisitMemberReferenceExpression() methods. All other methods are just neccesary for traversing the tree. 
We now have to start the vistor to traverse the AST in the Main() method:

&lt;pre class="brush:csharp"&gt;
...
// Here we will use the parser.CompilationUnit(AST)
CounterVisitor visitor = new CounterVisitor();
parser.CompilationUnit.AcceptVisitor(visitor, null);
Console.WriteLine("The file contains " + visitor.ClassCount + " class(es)");
Console.WriteLine("The file contains " + visitor.AssertionCount + " contract(s)");
...
&lt;/pre&gt;

For exploring the structure of the NRefactory AST you can use the NRefactoryDemo application, which is part of the SharpDevelop source code. You can enter source code and let the application create the according AST:

&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_NWVPQQln_9A/TMsyd_Up7mI/AAAAAAAAABo/L5RF67ltOeo/s1600/NRefactoryDemoScreenshot.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 242px; height: 320px;" src="http://2.bp.blogspot.com/_NWVPQQln_9A/TMsyd_Up7mI/AAAAAAAAABo/L5RF67ltOeo/s320/NRefactoryDemoScreenshot.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5533572057950449250" /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-1640292166543291476?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/1640292166543291476/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=1640292166543291476' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/1640292166543291476'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/1640292166543291476'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2010/10/example-for-parsing-c-code-with.html' title='Example for parsing C# code with the NRefactory library'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_NWVPQQln_9A/TMsyd_Up7mI/AAAAAAAAABo/L5RF67ltOeo/s72-c/NRefactoryDemoScreenshot.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-1346751865980163335</id><published>2009-11-29T20:27:00.021+01:00</published><updated>2011-12-27T15:44:06.112+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='AAA Syntax'/><category scheme='http://www.blogger.com/atom/ns#' term='Mocks; Arrange Act Assert Syntax'/><category scheme='http://www.blogger.com/atom/ns#' term='RhinoMocks'/><title type='text'>Stubs vs Mocks with Rhino Mocks</title><content type='html'>Recently I was asked: "What is the difference between Stubs and Mocks?" Martin Fowler has written a good article about that topic &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;"Mocks Aren't Stubs"&lt;/a&gt;. Also in the &lt;a href="http://www.ayende.com/Wiki/Rhino+Mocks+3.5.ashx"&gt;Rhino Mocks Wiki&lt;/a&gt; there is is comprehensive explanation.
&lt;p/&gt;
Besides the theoretical aspect you have to decide whether to use&lt;p/&gt; 
&lt;span style="font-weight: bold;"&gt;MockRepository.GenerateMock&lt;/span&gt; or &lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;MockRepository.GenerateStub&lt;/span&gt;&lt;p/&gt;
when you use the "Arrange, Act, Assert" syntax of Rhino Mocks. To find out the detailed differences I wrote some tests, which are all green. I defined expected behaviour or stubbed behaviour with different syntax combinations. The behaviour is not called in any test. Only in the tests with the "ExpectedException" attribute RhinoMocks throws an exception:

&lt;pre class="brush:csharp"&gt;
[Test]
[(typeof(ExpectationViolationException))]
public void VerifyAllExpectationsWithExpectMethodOnMock()
{
   IList listMock = MockRepository.GenerateMock&amp;lt;IList&gt;();
   listMock.Expect(x =&gt; x.Count).Return(10);

   listMock.VerifyAllExpectations();
}

[Test]
public void VerifyAllExpectationsWithExpectMethodOnStub()
{
   IList listStub = MockRepository.GenerateStub&amp;lt;IList&gt;();
   listStub.Expect(x =&gt; x.Count).Return(10);

   listStub.VerifyAllExpectations();
}

[Test]
public void VerifyAllExpectationsWithStubMethodOnMock()
{
   IList listMock = MockRepository.GenerateMock&amp;lt;IList&gt;();
   listMock.Stub(x =&gt; x.Count).Return(10);

   listMock.VerifyAllExpectations();
}

[Test]
public void VerifyAllExpectationsWithStubMethodOnStub()
{
   IList listStub = MockRepository.GenerateStub&amp;lt;IList&gt;();
   listStub.Stub(x =&gt; x.Count).Return(10);

   listStub.VerifyAllExpectations();
}

[Test]
[ExpectedException(typeof(ExpectationViolationException))]
public void AssertWasCalledWithMock()
{
   IList listMock = MockRepository.GenerateMock&amp;lt;IList&gt;();

   listMock.AssertWasCalled(x =&gt; { int temp = x.Count; });
}

[Test]
[ExpectedException(typeof(ExpectationViolationException))]
public void AssertWasCalledWithStub()
{
   IList listStub = MockRepository.GenerateStub&amp;lt;IList&gt;();

   listStub.AssertWasCalled(x =&gt; { int temp = x.Count; });
}
&lt;/pre&gt;

The conclusion from these tests are: If you need a mocking behaviour in Rhino Mocks that verifies your code under test, you have to use one of these two combinations of methods:

&lt;ol&gt;&lt;li&gt;&lt;span style="font-weight: bold;"&gt;GenerateMock&lt;/span&gt; with &lt;span style="font-weight: bold;"&gt;Expect(...)&lt;/span&gt; and &lt;span style="font-weight: bold;"&gt;VerifyAllExpectations()&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-weight: bold;"&gt;GenerateMock&lt;/span&gt;/&lt;span style="font-weight: bold;"&gt;GenerateStub&lt;/span&gt; with &lt;span style="font-weight: bold;"&gt;AssertWasCalled(...)&lt;/span&gt;&lt;/li&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-1346751865980163335?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/1346751865980163335/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=1346751865980163335' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/1346751865980163335'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/1346751865980163335'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2009/11/stubs-vs-mocks-with-rhino-mocks.html' title='Stubs vs Mocks with Rhino Mocks'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-4531837356366770675</id><published>2009-10-12T23:26:00.004+02:00</published><updated>2009-10-12T23:39:13.924+02:00</updated><title type='text'>LightContracts is a simple, small and lightweight library supporting 'Design by Contract'</title><content type='html'>Recently I created a project on Codeplex.com. It is called &lt;a href="http://lightcontracts.codeplex.com/"&gt;LightContracts&lt;/a&gt; and is a simple, small and lightweight library supporting 'Design by Contract' style of programming. It let you specify simple pre- and postconditions with a fluent API, without using an heavy AOP framework. It is developed in C#.

In his famous book "Object-Oriented Software Construction" Bertrand Meyer described a design technique called "Design by Contract" (DBC) which can improve software quality dramatically. His programming language Eiffel supports this design technique inherently. This valuable technique is universal and widely accepted and can be used regardless in which programming language you are developing. There are several tools available to use "Design By Contract" on the .NET platform ( E.g. ContractDriven.NET or ContractN). Recently Microsoft announced that its &lt;a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Code Contracts&lt;/a&gt; projects would be included as part of .Net 4.0.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;So why should I use LightContracts?&lt;/span&gt;
&lt;p/&gt;
All mentioned projects are quite heavyweight. They are using aspect-oriented programming (AOP) frameworks to inject code, require to inherit from a base class or need special tools and compiler settings. My observation is that 90% of all assertions are very simple and do not justify the use of heavy tools. &lt;a href="http://lightcontracts.codeplex.com/"&gt;LightContracts&lt;/a&gt; is a small DLL which can simply be referenced by any .NET project, without installing additional software. It has a fluent API which allows reading pre- and postconditions nearly like natural language. This allows simply copying these assertions into the method comments.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-4531837356366770675?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/4531837356366770675/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=4531837356366770675' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/4531837356366770675'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/4531837356366770675'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2009/10/lightcontracts-is-simple-small-and.html' title='LightContracts is a simple, small and lightweight library supporting &apos;Design by Contract&apos;'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-2857437449136574629</id><published>2009-02-11T21:55:00.020+01:00</published><updated>2010-10-24T14:07:24.415+02:00</updated><title type='text'>What is Design by Contract?</title><content type='html'>&lt;p&gt;This is the first article in a series which I started after I reasoned about &lt;a href="http://svengrand.blogspot.com/2009/02/why-is-design-by-contract-not-common.html"&gt;"Why is Design by Contract not common practice in Software Enineering?"&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; is a technique to specify the behavior of a class. It helps to communicate what effects methods will have and what the methods expect before they can be executed. &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; means that the caller of a class and the class itself make a contract, which is described as a set of assertions called Preconditions, Postconditions and Invariants.&lt;/p&gt;
&lt;p&gt;So the interface and the implementation of a class is enhanced with additional assertions. Preconditions define obligations for the caller of a method, which have to be satisfied before the method is called. Postconditions will guarantee the outcome of the method. Invariants apply to the class as a whole and define conditions which are valid at the end of each method call.&lt;/p&gt;

&lt;p&gt;I show an example in C# for preconditions and postconditions. Preconditions are commonly describes with the term 'require' and postconditions with the term 'ensure'. The property PrinterNames has the postcondition that the delivered list is not null. The method RemovePrinter has three preconditions:&lt;/p&gt;


&lt;pre class="brush:csharp"&gt;
public class Printers
{
    private List&amp;lt;string&gt; names;
    
    public Printers()
    {
        names = new List&amp;lt;string&gt;();
        names.Add("printer1");
        names.Add("printer2");
    }
    
    /// &amp;lt;summary&gt;
    /// List of printer names.
    /// Assertion.Ensure(names != null,"Result is not null");
    /// &amp;lt;/summary&gt;
    public List&amp;lt;string&gt; PrinterNames
    {
        get
        {
            Assertion.Ensure(names != null,"Result is not null");
            return names;
        }
    }
    
    /// &amp;lt;summary&gt;
    /// Remove a printer
    /// Assertion.Require(PrinterNames().Count &gt; 0,"There is at least one printer");
    /// Assertion.Require(printerIndex &gt;= 0,"printerIndex is not negative");
    /// Assertion.Require(printerIndex lessThan PrinterNames().Count ,"printerIndex is in range");
    /// &amp;lt;/summary&gt;
    public void RemovePrinter(int printerIndex)
    {
        Assertion.Require(PrinterNames.Count &gt; 0,"There is at least one printer");
        Assertion.Require(printerIndex &gt;= 0,"printerIndex is not negative");
        Assertion.Require(printerIndex &amp;lt; PrinterNames.Count ,"printerIndex is in range");
    
        names.RemoveAt(printerIndex);
    }

    ...
}
&lt;/pre&gt;

&lt;p&gt;For further information about &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; please refer to the &lt;a href="http://archive.eiffel.com/doc/manuals/technology/contract/"&gt;Eiffel web site&lt;/a&gt; or the book &lt;a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0136291554"&gt;Object-Oriented Software Construction&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;&lt;/p&gt;

&lt;p&gt;In the next article I will try to answer the question: What are the benefits of &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-2857437449136574629?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/2857437449136574629/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=2857437449136574629' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/2857437449136574629'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/2857437449136574629'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2009/02/what-is-design-by-contract.html' title='What is Design by Contract?'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-8370006849871186988</id><published>2009-02-04T14:35:00.007+01:00</published><updated>2009-02-13T10:07:01.111+01:00</updated><title type='text'>Why is Design by Contract not common practice in Software Enineering</title><content type='html'>Concerned with a lot of source code reviews over the last years, I have recognized that &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; is not a common practice in Software Engineering. Nearly all C++, Visual Basic, Java and C# source code I saw was designed and written without applying &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;. Thinking about the reasons for programmers not to use &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; I made a list with questions they may have:
&lt;ul&gt;&lt;li&gt;&lt;a href="http://svengrand.blogspot.com/2009/02/what-is-design-by-contract.html"&gt;What is &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;?&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;What are the benefits of &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;?&lt;/li&gt;&lt;li&gt;Do I need to use Eiffel as my programming language to apply &lt;span style="font-style: italic;"&gt;Design by Contract?&lt;/span&gt;&lt;/li&gt;&lt;li&gt;Do I have to spend a lot of effort for &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;?&lt;/li&gt;&lt;li&gt;In which situations should I use  &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt;?&lt;/li&gt;&lt;li&gt;Does &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; conflict with other design and implementation techniques like TDD and DDD?&lt;/li&gt;&lt;/ul&gt;If you have no or wrong answers for these questions you will probably not use &lt;span style="font-style: italic;"&gt;Design by Contract&lt;/span&gt; in your day to day programming work.  I will try to answer these questions in a series of articles and hope it will convince more programmers that &lt;span style="font-style: italic;"&gt;Design by Contract &lt;/span&gt;is an elegant technique to improve software quality.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-8370006849871186988?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/8370006849871186988/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=8370006849871186988' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/8370006849871186988'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/8370006849871186988'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2009/02/why-is-design-by-contract-not-common.html' title='Why is Design by Contract not common practice in Software Enineering'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-4083233693365945154</id><published>2009-01-15T23:50:00.009+01:00</published><updated>2010-10-24T14:09:58.348+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Design by Contract'/><title type='text'>Preconditions, Postconditions: Design by Contract for C#</title><content type='html'>Bertrand Meyer has described a design technique called "Design by Contract" (DBC) in his book &lt;a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0136291554"&gt;Object-Oriented Software Construction&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;. He also added support for this technique in his programming language Eiffel. Also other languages do not have a native support for this valuable technique, we nevertheless can apply this technique in all other languages. What we need is the possibility to define and execute assertions at runtime and we have to document the pre-, and postconditions in the header of our  methods.
For C# we only need a small helper class (comments are omitted):

&lt;pre class="brush:csharp"&gt;
public static class Assertion
{
    public static void Require(bool precondition, string conditionDescription)
    {
        if (!precondition)
        {
            throw new AssertException(ExceptionDescription("Precondition", conditionDescription));
        }
    }

    public static void Require(bool precondition, string descriptionFormat, params object[] descriptionParameters)
    {
        if (!precondition)
        {
            throw new AssertException(ExceptionDescription("Precondition", string.Format(CultureInfo.InvariantCulture, descriptionFormat, descriptionParameters)));
        }
    }

    public static void RequireIsNotNull(object toBeTested,string objectName)
    {
        if (toBeTested==null)
        {
            throw new AssertException(ExceptionDescription("Precondition", objectName + " is not null"));
        }
    }

    public static void Ensure( bool postcondition, string conditionDescription )
    {
        if ( ! postcondition )
        {
            throw new AssertException(ExceptionDescription("Postcondition",conditionDescription));
        }
    }

    public static void Ensure( bool postcondition, string descriptionFormat, params object[] descriptionParameters )
    {
        if ( ! postcondition )
        {
            throw new AssertException(ExceptionDescription("Postcondition",string.Format( CultureInfo.InvariantCulture, descriptionFormat, descriptionParameters ) ) );
        }
    }


    public static void Check( bool condition, string conditionDescription )
    {
        if ( ! condition )
        {
            throw new AssertException(ExceptionDescription("Condition",conditionDescription));
        }
    }

    public static void Check( bool condition, string descriptionFormat, params object[] descriptionParameters )
    {
        if ( ! condition )
        {
            throw new AssertException(ExceptionDescription("Condition",string.Format( CultureInfo.InvariantCulture, descriptionFormat, descriptionParameters ) ) );
        }
    }


    //
    // Private methods
    //

    private static string ExceptionDescription(string assertionType, string description)
    {
        return string.Format(CultureInfo.InvariantCulture, "{0} failed. The expectation was '{1}', but this is false.", assertionType, description);
    }

}
&lt;/pre&gt;

As important as checking the assertions at runtime is to allow a client of our class to read the preconditions and postconditions without inspecting the implementation of our methods. The simplest solution is to copy the assertions into then method comments:

&lt;pre class="brush:csharp"&gt;
public class PrinterDescription
{
    private XmlDocument printerXml;

    /// &amp;lt;summary&gt;
    /// Load the descripton from a xml file
    /// Assertion.RequireIsNotNull(printerDescriptionPath, "printerDescriptionPath");
    /// Assertion.Require(File.Exists(printerDescriptionPath), "File printerDescriptionPath exists");
    /// Assertion.Ensure(IsLoaded, "IsLoaded");
    /// &amp;lt;/summary&gt;
    public void Load(string printerDescriptionPath)
    {
        Assertion.RequireIsNotNull(printerDescriptionPath, 
            "printerDescriptionPath");
        Assertion.Require(File.Exists(printerDescriptionPath), 
            "File printerDescriptionPath exists");

        printerXml = new XmlDocument();
        printerXml.Load(printerDescriptionPath);

        Assertion.Ensure(IsLoaded, "IsLoaded");
    }

    /// &amp;lt;summary&gt;
    /// Is the description loaded?
    /// &amp;lt;/summary&gt;
    public bool IsLoaded
    {
        get
        {
            return printerXml != null;
        }
    }

    /// &amp;lt;summary&gt;
    /// Name of the printer
    /// Assertion.Require(IsLoaded, "IsLoaded");
    /// &amp;lt;/summary&gt;
    public string Name
    {
        get
        {
            Assertion.Require(IsLoaded, "IsLoaded");
            XPathNavigator nameNode = printerXml.CreateNavigator().SelectSingleNode("//PrinterName");
            return nameNode.Value;
        }
    }

}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-4083233693365945154?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/4083233693365945154/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=4083233693365945154' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/4083233693365945154'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/4083233693365945154'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2009/01/preconditions-postconditions-design-by.html' title='Preconditions, Postconditions: Design by Contract for C#'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-7804316019402166795</id><published>2008-12-18T00:00:00.017+01:00</published><updated>2010-10-24T14:16:29.119+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Design by Contract'/><title type='text'>Preconditions, Postconditions, Invariants : Design by Contract for Java #2</title><content type='html'>Recently I wrote about how to apply &lt;a href="http://svengrand.blogspot.com/2008/11/preconditions-postconditions-invariants.html"&gt;"Design by Contract" with Java&lt;/a&gt;. I proposed to use the assert statement of java, in case you do not want to set up some external tools like &lt;a href="http://www.contract4j.org/contract4j"&gt; Contract4J&lt;/a&gt;, &lt;a href="http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-cooltools.html"&gt;iContract&lt;/a&gt; or &lt;a href="http://csd.informatik.uni-oldenburg.de/%7Ejass/"&gt;Jass&lt;/a&gt;. After using the &lt;a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html"&gt;assert&lt;/a&gt; statement for a while I would recommend to use your own implementation of assertions instead like this:

&lt;pre class="brush:java"&gt;
public class Assertion {

 /**
  * Precondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Require(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Precondition.
  * @param objectToBeTested is an object we expect to be not null
  * @param objectName is the name of the variable we test.
  */
 public static void RequireNotNull(Object objectToBeTested,String objectName) {
     if (objectToBeTested == null) {
         throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
     }
 }

 /**
  * Postcondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Ensure(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Common condition to be used in the middle of methods
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Check(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
     }
 }
}
&lt;/pre&gt;

Why is the own implementation better than the assert statement?

&lt;ol&gt;&lt;li&gt;It does not make sense to switch off the runtime checks of assertions. We use assertions to simplify and avoid the error handling code in our methods. When it is possible to switch of assertions we loose this advantage, because we have to prepare our code to handle situations where the assertions are not checked.&lt;/li&gt;&lt;li&gt;We are not only profiting from assertions during development and testing but also when the software is deployed. Assertions uncover error conditions much clearer and with better error descriptions. The logs in a production system will contain the messages from assertions and will help to find the cause of the problem much faster. If we switch off the assertions the problems will occurring much later and the cause of the problem can only be found with much more effort,&lt;/li&gt;&lt;/ol&gt;

You can find details about "Design by Contract" in the famous book &lt;a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0136291554"&gt;Object-Oriented Software Construction&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; by Bertrand Meyer. &lt;p/&gt;

&lt;iframe src="http://rcm.amazon.com/e/cm?t=whcodo-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=0136291554&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;m=amazon&amp;lc1=0000FF&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-7804316019402166795?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/7804316019402166795/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=7804316019402166795' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/7804316019402166795'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/7804316019402166795'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/12/preconditions-postconditions-invariants.html' title='Preconditions, Postconditions, Invariants : Design by Contract for Java #2'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-5525004822405381924</id><published>2008-12-15T10:58:00.006+01:00</published><updated>2010-10-24T14:17:56.163+02:00</updated><title type='text'>Mocking an object with two interfaces</title><content type='html'>Currently I spend a lot of time with maintaining 'legacy' java code. That is not really funny :-(. To make the most out of it, I write as much unit tests as possible to gain some more confidence in the code and be prepared for future bugfixes and refactorings. I stumbled over a small problem, when I tried to mock an object which implements two interfaces. My 'system under test'(SUT) class TextManager uses an object which is an IReader and an IWriter at the same time. The object is only handed over once and the TextManager has to cast the IReader object into an IWriter object. The whole design is not really outstanding (to be polite) and I would have implemented it myself a little bit different.

&lt;pre class="brush:java"&gt;
public class TextManager {
   
   private IReader reader;
   
   public void readAndWrite() {
      String text = reader.read();
      text = "*" + text + "*";
      ((IWriter)reader).write(text);
   }
}
&lt;/pre&gt;

I wrote a unit test for the readAndWrite() method and recognized that I can't simply create a jMock object for the IReader/IWriter object. My colleague Henning found a simple an effective solution. In my test package I create a new interface called IReaderWriter which extends IReader and IWriter. Now I can create a mock object for this new interface which is able to work as a test double inside TextManager:

&lt;pre class="brush:java"&gt;
public void testReadAndWrite() {
    
    // Setup
    final IReaderWriter mock = context.mock(IReaderWriter.class);
    TextManager textManager = new TextManager(mock);
    context.checking(new Expectations() {{
        one(mock).read(); will(returnValue("test"));
        one(mock).write("*test*");
    }});
    
    // Exercise
    textManager.readAndWrite();
    
    // Verify
    context.assertIsSatisfied();
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-5525004822405381924?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/5525004822405381924/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=5525004822405381924' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5525004822405381924'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5525004822405381924'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/12/mocking-object-with-two-interfaces.html' title='Mocking an object with two interfaces'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-5252348058725057817</id><published>2008-11-27T21:40:00.038+01:00</published><updated>2010-11-04T13:39:47.550+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Design by Contract'/><title type='text'>Preconditions, Postconditions, Invariants : Design by Contract for Java</title><content type='html'>In his famous book &lt;a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&amp;amp;tag=whcodo-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0136291554"&gt;Object-Oriented Software Construction&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0136291554" alt="" style="border: medium none  ! important; margin: 0px ! important; display: none;" border="0" width="1" height="1" /&gt; Bertrand Meyer  described a design technique called "Design by Contract" (DBC) which can improve software quality dramatically. His programming language Eiffel supports this design technique inherently. This valuable technique is universal and widely accepted and can be used regardless in which programming language you are developing. To apply this technique in Java you need to define and execute assertions at runtime. The pre-, and postconditions of a method should also be part of the&lt;a href="http://java.sun.com/j2se/javadoc/"&gt; javadoc&lt;/a&gt; documentation.
&lt;p&gt;There are a lot of tools and framework which help you to apply DBC to your Java code. For example &lt;a href="http://oval.sourceforge.net/index.html"&gt;OVal&lt;/a&gt;,&lt;a href="http://www.contract4j.org/contract4j"&gt; Contract4J&lt;/a&gt;, which are using AspectJ, &lt;a href="http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-cooltools.html"&gt;iContract&lt;/a&gt; or &lt;a href="http://csd.informatik.uni-oldenburg.de/%7Ejass/"&gt;Jass&lt;/a&gt;, which are using a preprocessor for Java.
&lt;/p&gt;&lt;p&gt;In some circumstances it might be too much effort to apply one of these tools to you development project. Luckily there was a rudimentary support for testing assertions added to the Java language starting with release 1.4. The &lt;a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html"&gt;assert&lt;/a&gt; statement allows to define runtime checks inside your code.
With some simple conventions you can benefit from DBC without heavy tool support. Here is an example how to use the assertion mechanism of Java to apply "Design by Contract":

&lt;/p&gt;
&lt;pre class="brush:java"&gt;
/**
* Is the editor in the edit mode?
* @return True, if the editor is in the edit mode. Otherwise false.
*/
public boolean isInEditMode() {
 ...
}

/**
* Sets a new text.
* Precondition: isEditMode()
* Precondition: text != null
* Postcondition: getText() == text
* @param name
*/
public void setText(String text) {
 assert isInEditMode() : "Precondition: isInEditMode()";
 assert text != null : "Precondition: text != null";

 this.text = text;

 assert getText() == text : "Postcondition: getText() == text";
}


/**
* Delivers the text.
* Precondition: isEditMode()
* Postcondition: result != null
* @return
*/
public String getText() {

 assert isInEditMode() : "Precondition: isInEditMode()";

 String result = text;

 assert result != null : "Postcondition: result != null";
 return result;
}

&lt;/pre&gt;
So you can use "Design by Contract" effectively with three simple rules:&lt;p&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Use the &lt;a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html"&gt;assert&lt;/a&gt; mechanism of Java to check preconditions, postconditions and invariants at runtime.&lt;/li&gt;&lt;li&gt;Describe each &lt;a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html"&gt;assert&lt;/a&gt; with a string that starts either with "Precondition:", "Postcondition:" or "Invariant:" followed by the textual description of the assert expression.&lt;/li&gt;&lt;li&gt;Add each &lt;a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html"&gt;assert&lt;/a&gt; description string to the &lt;a href="http://java.sun.com/j2se/javadoc/"&gt;javadoc&lt;/a&gt; comment of the method&lt;/li&gt;&lt;/ul&gt;We can get a little more support, when we write our own pre- and postcondition class:

&lt;pre class="brush:java"&gt;
public class Assertion {

   /**
    * Precondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Require(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
       }
   }
  
   /**
    * Precondition.
    * @param objectToBeTested is an object we expect to be not null
    * @param objectName is the name of the variable we test.
    */
   public static void RequireNotNull(Object objectToBeTested,String objectName) {
       if (objectToBeTested == null) {
           throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
       }
   }

   /**
    * Postcondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Ensure(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
       }
   }

   /**
    * Common condition to be used in the middle of methods
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Check(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
       }
   }
}
&lt;/pre&gt;
Using this class instead of 'assert' has the advantage that we can't forget to switch on the runtime checking of the assertions with &lt;span style="font-style: italic;"&gt;-enableassertions&lt;/span&gt;. But keep in mind you still have to add method comments for the assertions. This is important, because the assertions should help the users of your class without forcing them to read your implementation details:

&lt;pre class="brush:java"&gt;
/**
* Sets a new text.
* Require: isEditMode()
* Require: text != null
* Ensure: getText() == text
* @param name
*/
public void setText(String text) {
 Assertion.Require(isInEditMode(),"isInEditMode()");
 Assertion.RequireNotNull(text, "text");

 this.text = text;

 Assertion.Ensure(getText() == text,"getText() == text");
}


/**
* Delivers the text.
* Require: isEditMode()
* Ensure: result != null
* @return
*/
public String getText() {

 Assertion.Require(isInEditMode(),"isInEditMode()");

 String result = text;

 Assertion.Ensure( result != null, "result != null";
 return result;
}

&lt;/pre&gt;
There is also an article &lt;a href="http://java.sun.com/developer/technicalArticles/JavaLP/assertions/"&gt;"Using Assertions in Java Technology"&lt;/a&gt; on the Sun Developer network.
See &lt;a href="http://svengrand.blogspot.com/2008/12/preconditions-postconditions-invariants.html"&gt;"Preconditions, Postconditions, Invariants : Design by Contract for Java #2"&lt;/a&gt; for further infos. &lt;p&gt;
&lt;iframe src="http://rcm.amazon.com/e/cm?t=whcodo-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;asins=0136291554&amp;amp;fc1=000000&amp;amp;IS2=1&amp;amp;lt1=_blank&amp;amp;m=amazon&amp;amp;lc1=0000FF&amp;amp;bc1=000000&amp;amp;bg1=FFFFFF&amp;amp;f=ifr" style="width: 120px; height: 240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0"&gt;&lt;/iframe&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-5252348058725057817?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/5252348058725057817/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=5252348058725057817' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5252348058725057817'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5252348058725057817'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/11/preconditions-postconditions-invariants.html' title='Preconditions, Postconditions, Invariants : Design by Contract for Java'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-6906645038133845076</id><published>2008-10-28T20:26:00.008+01:00</published><updated>2009-01-04T22:39:20.087+01:00</updated><title type='text'>CruiseControl, ClearCase and Dynamic Views</title><content type='html'>When I set up CruiseControl in our development infrastructure, I struggled a little bit with the ClearCase integration. I got a lot of information from the very good book &lt;a href="http://www.amazon.com/gp/product/0321356993?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321356993"&gt;Kevin A. Lee: IBM Rational(R) ClearCase(R), Ant, and CruiseControl: The Java(TM) Developer's Guide to Accelerating and Automating the Build Process&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321356993" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;. Unfortunately the book is not explicit whether to use dynamic or snapshot views in conjunction with CruiseControl. In our project most of the developers are using dynamic views to set up their private workspaces. So I tried to use dynamic views as well for CruiseControl. That was not a brilliant idea. Whats the problem?
When I set up CruiseControl as a windows service, I put the CruiseControl configuration file 'config.xml' into ClearCase. I recognized that the dynamic view with the 'config.xml' is not accessible by the service. Dynamic views have to be started with a cleartool command and then are mapped as drives. That must happen before the windows service is started. That seems not an straight forward solution when you are using the &lt;a href="http://wrapper.tanukisoftware.org/doc/english/index.html"&gt;Java Service Wrapper&lt;/a&gt;. Also mapped drives are not accessible by a windows service as long as no user is logged on. You can't use the drive letter, instead you have to use an URL.    
In the end it was much easier to set up CruiseControl with a snapshot view.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-6906645038133845076?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/6906645038133845076/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=6906645038133845076' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/6906645038133845076'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/6906645038133845076'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/10/cruisecontrol-clearcase-and-dynamic.html' title='CruiseControl, ClearCase and Dynamic Views'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-2201991206142755334</id><published>2008-08-26T22:34:00.010+02:00</published><updated>2009-01-04T22:41:25.937+01:00</updated><title type='text'>TDD and Layered Architecture</title><content type='html'>I just read the blog post of Jeffrey Palermo about the &lt;a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-3/"&gt;Onion Architecture&lt;/a&gt; (see also the similar pattern &lt;a href="http://alistair.cockburn.us/index.php/Hexagonal_architecture"&gt;Hexagonal architecture&lt;/a&gt;). Aspects of this patterns are used in an architecture our team defined for a healthcare information system.
&lt;p/&gt;
Interesting is Jeffrey's rationale for moving certain components to the outer layer:
The "infrastructure is pushed out to the edges where no business logic code couples to it", because "this code is most likely to change frequently as the application goes through years of maintenance". I think this is absolutely true.
&lt;p/&gt;
Eric Evans presented a pattern called Layered Architecture in his book &lt;a href="http://www.amazon.com/gp/product/0321125215?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321125215"&gt;Domain-Driven Design: Tackling Complexity in the Heart of Software&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321125215" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;. His rationale for for moving certain components to the outer layer: The  domain model should be separated from the technical details so it contains only the concepts we want to discuss with the domain experts. That is also a very good guideline when we have decide in which layer a certain piece of code belongs.
&lt;p/&gt;
A third rational for moving certain components to the outer layer we get when we are using TDD: All components which can't be tested by &lt;span style="font-style:italic;"&gt;pure unit tests&lt;/span&gt; should be placed on the outer layer. These components should be as thin as possible, because we want to test as much code as possible by &lt;span style="font-style:italic;"&gt;pure unit tests&lt;/span&gt;. Components which do not have an API defined in the implementation language like GUI components, Windows Services, Wrapper to other languages and platforms and so on are candidates for the outer layer. Here we can't use &lt;span style="font-style:italic;"&gt;pure unit tests&lt;/span&gt;. Slower or more awkward tests type have to be used. Data access components for databases contain or generate SQL statements. These data access components should be tested in conjunction with the real database to verify the correctness of the SQL statements. I call these tests &lt;span style="font-style:italic;"&gt;database unit tests&lt;/span&gt;. They are much slower than the &lt;span style="font-style:italic;"&gt;pure unit tests&lt;/span&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-2201991206142755334?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/2201991206142755334/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=2201991206142755334' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/2201991206142755334'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/2201991206142755334'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/08/tdd-and-layered-architecture.html' title='TDD and Layered Architecture'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-9127556011073892602</id><published>2008-07-25T11:51:00.030+02:00</published><updated>2010-10-24T14:23:44.242+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='CruiseControl'/><category scheme='http://www.blogger.com/atom/ns#' term='log4j'/><title type='text'>Configure CruiseControl Logging</title><content type='html'>If you have problems to get your CruiseControl running you may want to see some more log output. For example when your &amp;lt modificationset&amp;gt configuration does not work as expected, you want to see which commands are submitted for retrieveing the modifications in your source code repository.
To switch on more log output create a &lt;span style="font-weight: bold;"&gt;log4j.properties&lt;/span&gt; file and place it in the CruiseControl folder side by side with the CruiseControl.bat and the config.xml file. The file may contain a log4j configuration like:

&lt;pre class="brush:plain"&gt;
# Set root logger level to ERROR (default)
log4j.rootLogger=ERROR, CONSOLE, FILE
log4j.logger.net.sourceforge.cruisecontrol=INFO
log4j.logger.net.sourceforge.cruisecontrol.sourcecontrols=DEBUG

# A1 is to console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n

# FILE is file logger with rotation
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n
log4j.appender.FILE.File=cruisecontrol.log
log4j.appender.FILE.MaxFileSize=5000KB
log4j.appender.FILE.MaxBackupIndex=4
&lt;/pre&gt;

Modify the &lt;span style="font-weight: bold;"&gt;CruiseControl.bat&lt;/span&gt; which starts the CruiseControl build loop.
Add the command line parameter "-Dlog4j.configuration=file:./log4j.properties"
to the call of the java application:

&lt;pre class="brush:bash"&gt;
set CCDIR=%~dp0

:checkJava
if not defined JAVA_HOME goto noJavaHome
set JAVA_PATH="%JAVA_HOME%\bin\java"
set CRUISE_PATH=%JAVA_HOME%\lib\tools.jar
goto setCruise

:noJavaHome
echo WARNING: You have not set the JAVA_HOME environment variable. Any tasks relying on the tools.jar file (such as "&amp;lt javac&amp;gt") will not work properly.
set JAVA_PATH=java

:setCruise
set LIBDIR=%CCDIR%lib

set LAUNCHER=%LIBDIR%\cruisecontrol-launcher.jar

set EXEC=%JAVA_PATH% %CC_OPTS% -Djavax.management.builder.initial=mx4j.server.MX4JMBeanServerBuilder -Dlog4j.configuration=file:./log4j.properties -jar "%LAUNCHER%" %* -jmxport 8001 -webport 8080 -rmiport 1099
echo %EXEC%
%EXEC%
&lt;/pre&gt;

With this setup you get more detailed output concerning the access towards the source code repository.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-9127556011073892602?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/9127556011073892602/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=9127556011073892602' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/9127556011073892602'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/9127556011073892602'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/07/configure-cruisecontrol-logging.html' title='Configure CruiseControl Logging'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-5569501459591581367</id><published>2008-05-22T21:13:00.029+02:00</published><updated>2009-01-15T23:17:09.481+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='xUnit'/><category scheme='http://www.blogger.com/atom/ns#' term='Test Pattern'/><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>A New xUnit Test Pattern</title><content type='html'>Inspired by the Gerard Meszaros book &lt;a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0131495054"&gt;xUnit Test Patterns: Refactoring Test Code&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0131495054" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;, I have written down a pattern, which I used already many times:

&lt;h1&gt;Own Library Interface&lt;/h1&gt;

Also known as: 'Skin and Wrap the API' [&lt;a href="http://www.amazon.com/gp/product/0131177052?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0131177052"&gt;Working Effectively with Legacy Code&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0131177052" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;"/&gt;by Michael Feathers]
&lt;p/&gt;
&lt;span style="font-style: italic;"&gt;How can we make a code testable, when the code depends on a library class, which can't be replaced by a 'Test Double'?&lt;/span&gt;
&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;We write our own interface that exactly mirrors the API of the library class. In our system under test (SUT) we use the interface instead of the library class itself.&lt;/span&gt;
&lt;p/&gt;

&lt;div style="text-align: center;"&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_NWVPQQln_9A/SDXJtbXp7uI/AAAAAAAAAAY/JZU87LU4F7Y/s1600-h/Pattern.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;" src="http://2.bp.blogspot.com/_NWVPQQln_9A/SDXJtbXp7uI/AAAAAAAAAAY/JZU87LU4F7Y/s320/Pattern.png" alt="" id="BLOGGER_PHOTO_ID_5203286726774746850" border="0" /&gt;&lt;/a&gt;The code we want to test is the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;system under test (SUT)&lt;/a&gt;. It references a &lt;a href="http://xunitpatterns.com/DOC.html"&gt;depended-on component (DOC)&lt;/a&gt; library class.
&lt;p/&gt;

&lt;/div&gt;Some library classes do not inherit from an interface, they do not declare their methods as virtual or they provide static methods, so it is not possible to introduce a &lt;span&gt;&lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test Double&lt;/a&gt;&lt;/span&gt; to the SUT via &lt;a href="http://xunitpatterns.com/Dependency%20Injection.html"&gt;&lt;span&gt;Dependency Injection&lt;/span&gt;&lt;/a&gt; or &lt;a href="http://xunitpatterns.com/Dependency%20Lookup.html"&gt;&lt;span&gt;Dependency Lookup&lt;/span&gt;&lt;/a&gt; to replace the library class during testing. This problem arises very often when we need to use system or third party libraries (like the .NET framework) where we can’t modify the library classes and have to use them as they are.
Library designers prefer to use class-based APIs instead of interfaces, because they can be evolved in later versions of the library. If they want to add members to a library interface in a later version , they would break existing code [&lt;a href="http://www.amazon.com/gp/product/0321545613?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321545613"&gt;Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321545613" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;by Abrams and Cwalina].
Very often the SUT can’t be tested together with the library class, because the library class can’t be used in the test environment. The reason may be that the library class will not return values needed for the test or executing it would have undesirable side effects.

&lt;h2&gt;How it Works&lt;/h2&gt;
We write our own interface which mirrors the API of a library class we are using in our SUT. Our own interface does not need to contain the complete API of the library class but may contain only the subset we are requiring for our SUT.
We implement a thin wrapper for the library class which inherits from our own interface. The wrapper will contain no logic. Each method can simply be forwarded to the library class, because the signatures of our own interface are the same as the library class.
The SUT must use the interface instead of the library class itself. The SUT will be initialized with a concrete object via &lt;a href="http://xunitpatterns.com/Dependency%20Injection.html"&gt;&lt;span&gt;Dependency Injection&lt;/span&gt;&lt;/a&gt; or &lt;a href="http://xunitpatterns.com/Dependency%20Lookup.html"&gt;&lt;span&gt;Dependency Lookup&lt;/span&gt;&lt;/a&gt;. In the production environment the thin wrapper is used. In the test environment we can replace the thin wrapper with a &lt;span&gt;&lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test Double&lt;/a&gt;&lt;/span&gt;.

&lt;h2&gt;When to Use It&lt;/h2&gt;
We have to use the &lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;Own Library Interface&lt;/a&gt; when we use a third party library class in our SUT which has both of the two following characteristics:

&lt;ul&gt;&lt;li&gt;The dependency on the library class prevents us from executing the SUT in a test environment. It may be plain impossible, too slow,  too complex or too expensive to prepare a test environment for testing the SUT together with the library class.&lt;/li&gt;&lt;li&gt;The library class can not be replaced by a &lt;span&gt;&lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test Double&lt;/a&gt;&lt;/span&gt;, because it does not inherit from an interface, it does not declare its methods as virtual or it has static methods.&lt;/li&gt;&lt;/ul&gt;These circumstances very often lead to the smell &lt;span&gt;&lt;a href="http://xunitpatterns.com/Developers%20Not%20Writing%20Tests.html"&gt;Developers Not Writing Tests&lt;/a&gt;&lt;/span&gt;. The SUT will be declared as untestable. Also TDD beginners often stumble over this problem and get the impression that TDD is not applicable to real world examples.

&lt;h2&gt;Implementation Notes&lt;/h2&gt;
Library classes which define the API for operating system mechanisms (registry, event log, services), the API for hardware sub systems (network infrastructure) or the API to other software components (SMTP server, POP3 server) are candidates for the usage of the &lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;Own Library Interface&lt;/a&gt; pattern. Preparing a fixture for testing own classes which are using such library classes may be plain impossible, too slow,  too complex or too expensive. See &lt;a href="http://svengrand.blogspot.com/2008/03/recently-colleague-of-mine-which-is.html"&gt;TDD for Beginners&lt;/a&gt; as an detailed example for the usage of the &lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;Own Library Interface&lt;/a&gt;&lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;&lt;/a&gt; pattern.
We do not need to use the &lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;Own Library Interface&lt;/a&gt; pattern, when we can test our SUT together with the library class. For example the &lt;span style="font-style: italic;"&gt;File&lt;/span&gt; or &lt;span style="font-style: italic;"&gt;Directory&lt;/span&gt; classes from the .NET framework can easily be tested together with the SUT, because preparing files and directories during test setup as well as checking them after exercising the SUT  is quite  easy.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-5569501459591581367?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/5569501459591581367/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=5569501459591581367' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5569501459591581367'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5569501459591581367'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html' title='A New xUnit Test Pattern'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_NWVPQQln_9A/SDXJtbXp7uI/AAAAAAAAAAY/JZU87LU4F7Y/s72-c/Pattern.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-5110810274616415870</id><published>2008-04-19T23:53:00.015+02:00</published><updated>2009-01-04T22:27:36.227+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='software'/><category scheme='http://www.blogger.com/atom/ns#' term='books'/><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>To become a better programmer</title><content type='html'>I think some books might help to become a better programmer. This is my personal list:
&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides,&lt;/span&gt; &lt;a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201633612"&gt;Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0201633612" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
The book came out, when I finished university and started by first full time job as an programmer. The theory of patterns  taught me about the importance of names for concepts and the importance of communication with other developers. Five years later I went to a conference just to see Erich Gamma. Of course he spoke about patterns, but combined his talk with TDD, JUnit and a comparison of Java and C#. The lecture was not very long but brilliant. That was the first time I heard about TDD and got test infected.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Martin Fowler &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0321127420?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321127420"&gt;Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321127420" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
I read the book, when I already worked on enterprise applications for several years. The book was an revelation. Most of the problems described there I know very well, but now I got names for them and so many alternative solutions. This book gave me the possibility to better reflect about design and architecture decisions. This book was partly responsible that I became the architect of our project.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Martin Fowler, Kent Beck, John Brant, and William Opdyke &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201485672"&gt;Refactoring: Improving the Design of Existing Code (Addison-Wesley Object Technology Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0201485672" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
Beside the refactorings and the theory, this book helped me so much to convince my team members of the benefits of TDD.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Eric Evans &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0321125215?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321125215"&gt;Domain-Driven Design: Tackling Complexity in the Heart of Software&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321125215" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
Brilliant book! The concept of the 'ubiquitous language' helped me very much for my day to day work. Using the 'Layered Architecture' pattern to separate technical details from the business concepts helped to better organize our software components.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Bertrand Meyer &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0136291554"&gt;Object-Oriented Software Construction (Book/CD-ROM) (2nd Edition) (Prentice-Hall International Series in Computer Science)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
Maybe this is the oldest book in my collection. Nevertheless it  is still useful for me. I use assertions and 'programming by contract' nearly every day. This concepts can be used together with TDD very well. Even if you do not use Eiffel as the programming language, you can implement an assertion class for every other programming language in  several minutes.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Mary Poppendieck and Tom Poppendieck &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0321150783?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321150783"&gt;Lean Software Development: An Agile Toolkit (Agile Software Development Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321150783" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
I never believed that other industries can teach the software industry about new concepts. After reading this book I know that the people from Toyota were very clever and the software people can learn a lot from them. Now I always try to find some 'waste' in our processes.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Kent Beck &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0321278658?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321278658"&gt;Extreme Programming Explained: Embrace Change (2nd Edition) (XP Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321278658" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
Although I never had the chance to work in a full blown XP project, this book is still a constant source of inspiration.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Kent Beck &lt;/span&gt;&lt;a href="http://www.amazon.com/gp/product/0321146530?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321146530"&gt;Test Driven Development: By Example (Addison-Wesley Signature Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0321146530" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
If you start with TDD, read this book.

&lt;p/&gt;
&lt;span style="font-weight: bold;"&gt;Gerard Meszaros &lt;/span&gt; &lt;a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&amp;tag=whcodo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0131495054"&gt;xUnit Test Patterns: Refactoring Test Code (Addison-Wesley Signature Series)&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&amp;l=as2&amp;o=1&amp;a=0131495054" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;
&lt;p/&gt;
If you already worked a little bit with TDD, then read this book.
&lt;p/&gt;

I'm very sure everyone has its own list. I would be glad to here from other people about their favorite books.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-5110810274616415870?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/5110810274616415870/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=5110810274616415870' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5110810274616415870'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/5110810274616415870'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/04/to-become-better-programmer.html' title='To become a better programmer'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-308938520654874970</id><published>2008-03-31T22:33:00.005+02:00</published><updated>2008-03-31T22:48:23.960+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='codeproject'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Mail Attachments without files</title><content type='html'>I just received a comment about an article I wrote for www.codeproject.com. The article describes how to create and send mails with attachments in C# (no rocket science :-). The attachments are created in-memory without any file system access by the use of a memory stream:
&lt;a href="http://www.codeproject.com/KB/IP/InMemoryMailAttachment.aspx"&gt;http://www.codeproject.com/KB/IP/InMemoryMailAttachment.aspx&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-308938520654874970?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/308938520654874970/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=308938520654874970' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/308938520654874970'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/308938520654874970'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/03/mail-attachments-without-files.html' title='Mail Attachments without files'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1084762708281241901.post-805106105175779348</id><published>2008-03-28T23:22:00.006+01:00</published><updated>2010-10-24T14:45:03.378+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>TDD for Beginners</title><content type='html'>Recently a colleague of mine, which is a quite experienced programmer, wants to write his first code using TDD. It takes only minutes until he encountered the first obstacle.
It seems that TDD is quite difficult for beginners. I will describe some of the problems and show code examples to help TDD beginners to become familiar faster with this excellent technique. Based on these kinds of experiences I described also a pattern called &lt;a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"&gt;&lt;span style="font-style: italic;"&gt;Own Library Interface&lt;/span&gt;&lt;/a&gt; which  is applicable in the situation described below.

My colleague needs to implement a background service, which monitors a database. The background service has to send notifications to one or more external receivers. He designed an EmailSender class, which can be initialized with all email related information like the smtp server, the sender and the receiver email addresses. Now he wants to write the SendToAll() method, which only needs some information for the receivers:

&lt;pre class="brush:csharp"&gt;
public void SendToAll(string subject, string details)
&lt;/pre&gt;

He has already poked around in the .NET framework and has found the SmtpClient class for easy sending of emails. He wants to use this class in his own EmailSender class. He knows that he first has to write a test, if he wants to follow the TDD principles, before he can begin with the implementation.
He starts to implement the test method, which should verify the successful execution of the method:

&lt;pre class="brush:csharp"&gt;
[TestFixture]
public class EmailSenderFixture
{
  [Test]
  public void SendToAll()
  {
    // Setup
    EmailSender sender = new EmailSender();
    ...

    // Exercise
    sender.SendToAll("TestSubject","TestDetails");

    // Verify
    // ?
  }
}
&lt;/pre&gt;
How can he verify the outcome of the SendToAll method? One solution would be to let his own class send emails to an email account and then checking the correct behaviour of his class by retrieving the emails via POP3. This solution has some disadvantages:
&lt;ul&gt;&lt;li&gt;The tests would be very slow.&lt;/li&gt;&lt;li&gt;The tests need special preconditions (context) to run (smtp server, email account).&lt;/li&gt;&lt;li&gt;The tests would not only cover the functionality of the class alone but also the .NET framework class SmtpClient. Framework classes do not need to be tested, because it can be assumed that they work correctly. (Event if they do not, we can't do anything about that)&lt;/li&gt;&lt;li&gt;The retrieval of emails via the POP3 protocol has to be implemented only for the automated tests, which are currently not need for the production system.&lt;/li&gt;&lt;/ul&gt;I would always prefer to use state verification, that means verifying the outcome of a method by inspecting the state of the manipulated object, but in this case the class has no state which can be verified. As we have seen, the state verification of a backdoor (a real email account) has many drawbacks.

An other solution would be the use of a mock object as a test double for the SmtpClient. Currently our SendToAll method is empty and uses no dependent object, which can be mocked out. My colleague decided to use mock objects to verify the behaviour of his class. He starts implementing an initial version of his method, before he finishes his test method. The initial version looks like this:

&lt;pre class="brush:csharp"&gt;
public class EmailSender
{
 private SmtpClient smtpClient;
 ...
 public EmailSender(
  SmtpClient smtpClient,
  string host,
  int port,
  string from,
  params string[] recipients)
 {
  this.smtpClient = smtpClient;
  this.from = from;
  this.port = port;
  this.host = host;
  this.recipients = recipients;
 }

 public void SendToAll(string subject, string details)
 {
  smtpClient.Host = host;
  smtpClient.Port = port;

  foreach (string recipient in recipients)
  {
      smtpClient.Send(
   from,
   recipient,
   subject,
   details);
  }
 }
}
&lt;/pre&gt;

He already injected the SmtpClient object via the constructor and uses this object to send the emails. This is a nice try but unfortunately he can't mock out the SmtpClient yet. The SmtpClient framework class does not inherit from any interface nor does it declare its methods as virtual, so he can't create a mock object for SmtpClient. This lack of 'mockability' is quite common for most of the classes in the Microsoft .NET framework. Cwalina and Abrams [1] are describing rules for the design of framework classes: "Class-based APIs can be evolved with much greater ease than interface-based APIs because it is possible to add members to a class without breaking existing code". From the perspective of framework designers it is absolute understandable, that most of the classes do not use interfaces. As unit test authors we have to write our own interfaces which mirror the API of the framework classes as close as possible and later write very thin wrappers inheriting from our interface. My colleague only uses two properties and one method of the SmtpClient class. He only needs to declare these members in his new interface:

&lt;pre class="brush:csharp"&gt;
public interface ISmtpClient
{
 string Host { get; set; }
 int Port { get; set; }
 void Send(string from, string recipients,
      string subject, string body);
}
&lt;/pre&gt;

Now he can slightly modify his EmailSender class to use the ISmtpClient interface instead of SmtpClient framework class directly:

&lt;pre class="brush:csharp"&gt;
public class EmailSender
{
 private ISmtpClient smtpClient;
 ...
 public EmailSender(
  ISmtpClient smtpClient,
  string host,
  int port,
  string from,
  params string[] recipients)
 {
  this.smtpClient = smtpClient;
  ...
 }
 ...
}
&lt;/pre&gt;

He finishes his test and verifies the behaviour of the EmailSender class. He is using the NMock2 framework for his mock object:

&lt;pre class="brush:csharp"&gt;
using NMock2;
...
[Test]
public void SendToAll()
{
 // Setup
 Mockery mocks = new Mockery();
 ISmtpClient smtpClientMock = mocks.NewMock&amp;lt;ISmtpClient&gt;();

 EmailSender sender = new EmailSender(
  smtpClientMock,
  "smtp.test.com",
  25,
  "sender@test.com",
  "receiver1@test.com",
  "receiver2@test.com");

 Expect.Once.On(smtpClientMock).
  SetProperty("Host").
  To("smtp.test.com");
  Expect.Once.On(smtpClientMock).
  SetProperty("Port").To(25);

 // We expect that the Send method is called for every recipient
 Expect.Once.On(smtpClientMock).Method("Send").
  With("sender@test.com", "receiver1@test.com",
       "TestSubject", "TestDetails");
  Expect.Once.On(smtpClientMock).Method("Send").
  With("sender@test.com", "receiver2@test.com",
       "TestSubject", "TestDetails");

 // Exercise
 sender.SendToAll("TestSubject", "TestDetails");

 // Verify
 mocks.VerifyAllExpectationsHaveBeenMet();
}
&lt;/pre&gt;

This test runs very fast and it does not need any special context like an smtp server or an email account. Before he can use the EmailSender class in a production environment he has to implement a thin wrapper around the SmtpClient framework class:

&lt;pre class="brush:csharp"&gt;
public class SmtpClientWrapper : ISmtpClient
{
 private SmtpClient smtpClient = new SmtpClient();

 public string Host
 {
  get { return smtpClient.Host; }
  set { smtpClient.Host = value; }
 }

 public int Port
 {
  get { return smtpClient.Port; }
  set { smtpClient.Port = value; }
 }

 public void Send(string from,
  string recipients,
  string subject,
  string body)
 {
  smtpClient.Send(from, recipients, subject, body);
 }
}
&lt;/pre&gt;

This wrapper needs not to be tested, because it adds no new functionality to the framework class. The EmailSender class can now be used in the background service:

&lt;pre class="brush:csharp"&gt;
public void Run()
{
 EmailSender sender = new EmailSender(
  new SmtpClientWrapper(),
  "smtpserver.xy.com",
  25,
  "sender@xy.com",
  "receiver1@xy.com",
  "receiver2@xy.com");

 while (!stopped)
 {
  // Check something
  string checkResult = Check();

  // Send email
  sender.SendToAll("Check", checkResult);

  // Sleep for 20 minutes
  Thread.Sleep(20*60*1000);
 }
}
&lt;/pre&gt;

&lt;p&gt;
&lt;/p&gt;&lt;span style="font-weight: bold;"&gt;Conclusion
&lt;/span&gt;&lt;p&gt;
Applying TDD as a new technique for software development is sometimes not easy for beginners. When we need to write software, which has to use framework classes, we need to use mock objects and we eventually have to introduce new interfaces and wrappers. The same problems we saw with SmtpClient arise when we have to use classes like System.ServiceProcess.ServiceController, System.Diagnostics.EventLog, System.DirectoryServices.ActiveDirectory.Domain, System.Net.NetworkInformation.NetworkInterface, System.Net.Sockets.Socket, System.Environment, Microsoft.Win32.Registry just to name a few. I hope this article can help a little bit to overcome the first hurdles when using TDD the first time.
&lt;/p&gt;&lt;p&gt;
&lt;span style="font-weight: bold;"&gt;References&lt;/span&gt;&lt;/p&gt;&lt;p&gt;
[1]  Cwalina, K., Abrams, B.: Framework Design Guidelines, Microsoft .NET Development Series, Addison Wesley, 2006&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1084762708281241901-805106105175779348?l=svengrand.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://svengrand.blogspot.com/feeds/805106105175779348/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=1084762708281241901&amp;postID=805106105175779348' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/805106105175779348'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1084762708281241901/posts/default/805106105175779348'/><link rel='alternate' type='text/html' href='http://svengrand.blogspot.com/2008/03/recently-colleague-of-mine-which-is.html' title='TDD for Beginners'/><author><name>Sven</name><uri>http://www.blogger.com/profile/02929879501185148654</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://4.bp.blogspot.com/_NWVPQQln_9A/TU03WvkylgI/AAAAAAAAAB8/YO_CTKw-K34/s220/Rostami-R-_Boris_SvenGrand.jpg'/></author><thr:total>0</thr:total></entry></feed>
