tag:blogger.com,1999:blog-10847627082812419012024-03-05T22:12:49.951+01:00while(coding){DoTDD();}Notes about Software Engineering, Test-Driven Development, C#.NET, Java and ...Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.comBlogger27125tag:blogger.com,1999:blog-1084762708281241901.post-23510364840484340402014-01-19T17:29:00.001+01:002014-11-03T23:02:24.679+01:00Unit testing code with timersAttempts to unit test code which uses a timer most often lead to tests like:<br />
<br />
<pre class="brush:csharp">[Test]
public void SlowAndFragileTest()
{
// Setup
dataProviderMock = MockRepository.
GenerateMock<IDataProvider>();
systemUnderTest = new PollCommand(dataProviderMock);
// Act
systemUnderTest.StartPoll();
// Make sure the timer has been executed at least
// once. The action is started after 10 seconds.
Thread.Sleep(11000);
// Assert
dataProviderMock .AssertWasCalled(
x=>x.Retrieve());
}
</pre>
<br />
This testing approach is problematic. The test always takes 11 seconds, which is far to slow for a unit test. Depending on the timer used it is not guaranteed at what exact point in time the action is triggered. The action itself also takes time, so we can't be 100% sure that the action is finished when we test reaches the assert statement.<br />
<br />
<h4>
Solution - Test code with timers in one thread</h4>
We can separate the timer mechanics from our code and use a special timer which executes the action on the current thread. We can also tell this timer how much time has passed by:
<br />
<pre class="brush:csharp">[Test]
public void ShouldRetrieveDataEvery10Seconds()
{
// Arrange
timerStub = new DeterministicTimer();
dataProviderMock = MockRepository.
GenerateMock<IDataProvider>();
systemUnderTest = new PollCommand(
timerStub,
dataProviderMock);
// Act
systemUnderTest.StartPoll();
// Now execute the timer actions on
// the current thread.
timerStub.TickSeconds(30);
// Assert
dataProviderMock.AssertWasCalled(
x=>x.Retrieve(),
y=>y.Repeat.Times(3));
}
</pre>
<br />
This test is very fast and takes fractions of a second. This test is also robust because every code is executed on the current thread.<br />
Our PollComand class we are testing now looks very simple:
<br />
<pre class="brush:csharp">private readonly ITimer timer;
public void StartPoll()
{
timer.StartTimer(
RetrieveData,
new TimeSpan(0, 0, 0, 10));
}
private void RetrieveData()
{
retrievedDate = dataProvider.Retrieve();
}
</pre>
<br />
The DeterministicTimer is straight forward:
<br />
<pre class="brush:csharp">
public class DeterministicTimer : ITimer
{
private Action action;
private TimeSpan intervall;
private bool isStarted;
private TimeSpan elapsedTime;
#region ITimer methods
public void StartTimer(Action action, TimeSpan intervall)
{
isStarted = true;
this.action = action;
this.intervall = intervall;
elapsedTime = new TimeSpan();
}
public bool IsStarted()
{
return isStarted;
}
public void StopTimer()
{
isStarted = false;
}
#endregion
public void TickSeconds(int seconds)
{
TimeSpan newElapsedTime = elapsedTime + new TimeSpan(0, 0, 0, seconds);
if (isStarted)
{
long executionCountBefore = elapsedTime.Ticks / intervall.Ticks;
long executionCountAfter = newElapsedTime.Ticks / intervall.Ticks;
for (int i = 0; i < executionCountAfter - executionCountBefore; i++)
{
action();
}
}
elapsedTime = newElapsedTime;
}
}
</pre>
See also my <a href="http://msdn.microsoft.com/en-us/magazine/dn818494.aspx">MSDN Magazine article</a> for general remarks about unit testing multithreaded code.
Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-41703541936154489392014-01-05T21:09:00.000+01:002014-11-03T23:02:54.316+01:00Unit testing multi-threaded codeAttempts to unit test multi-threaded code most often lead to tests like:
<br />
<pre class="brush:csharp">[Test]
public void FragileAndSlowTest()
{
// Setup
SystemUnderTest sut = new SystemUnderTest();
// Start new thread
sut.DoAsync();
// Make sure the thread has finished execution
Thread.Sleep(2000);
// Assert
...
}
</pre>
This testing approach has two disadvantages:<br />
<ol>
<li>From time to time this test fails when the thread is not started and executed within two seconds. This can happen for example when the PC is busy with other activities. We can call these kinds of tests <a href="http://xunitpatterns.com/Fragile%20Test.html">fragile</a>. </li>
<li>This test takes alway at least two seconds to run. This is far to slow for a unit test.</li>
</ol>
<h4>
Solution 1 - Call functionality without multi-threading code </h4>
We can execute the method which is executed in the new thread directly excluding the concurrency aspect. Either we make the method 'public' or we extract the functionality of the method into a separate class and then call that method directly from the test:
<br />
<pre class="brush:csharp">[Test]
public void TestWithoutTouchingThreadingCode()
{
// Setup
SystemUnderTest sut = new SystemUnderTest();
// Directly call synchronous method
// which is internally called by DoAsync()
sut.Do();
// Assert
...
}
</pre>
Advantages:<br />
<ul>
<li>We are forced to separate concerns in the code (functionality and concurrency) leading to better maintainability. </li>
</ul>
Disadvantages:<br />
<ul>
<li>We have to make the private method <span style="font-family: "Courier New",Courier,monospace;">Do()</span> public for the purpose of testing. In production we would never call the method from outside so we are violating the <a href="http://en.wikipedia.org/wiki/Information_hiding">information hiding</a> principle. </li>
<li>The <span style="font-family: "Courier New",Courier,monospace;">DoAsync()</span> method is not executed in any test. If we have a more complex concurrency behaviour than in the example like starting an additional thread when the first thread is finished, we will also not test this behaviour. </li>
</ul>
<h4>
Solution 2 - Test multi-threading code in one thread</h4>
We can replace the thread starting object with a test stub, which executes the <span style="font-family: "Courier New",Courier,monospace;">Do()</span> method in the same thread as the unit test. The example shows C# code using tasks from the .NET Framework Class Library. The default <span style="font-family: "Courier New",Courier,monospace;">TaskScheduler</span> can be replaced with our own implementation called <span style="font-family: "Courier New",Courier,monospace;">DeterministicTaskScheduler</span>. The test executes all code in the current thread:
<br />
<pre class="brush:csharp">[Test]
public void TestMultiThreadingCodeSynchronously()
{
// Arrange
DeterministicTaskScheduler taskScheduler =
new DeterministicTaskScheduler();
SystemUnderTest sut =
new SystemUnderTest(taskScheduler);
// Execute multi-threaded code and
// return immediately.
sut.DoAsync();
// Now execute the new task on
// the current thread.
taskScheduler.RunTasksUntilIdle();
// Assert
...
}
</pre>
See <a href="http://svengrand.blogspot.de/2013/12/unit-testing-c-code-which-starts-new.html">this blog post</a> for a detailed description of the <span style="font-family: "Courier New",Courier,monospace;">DoAsync()</span> implementation and the <span style="font-family: "Courier New",Courier,monospace;">DeterministicTaskScheduler</span>. <br />
The concept also works very well for code using timers:<br />
<pre class="brush:csharp">[Test]
public void ShouldRetrieveDataEverySecond()
{
// Arrange
timerStub = new DeterministicTimer();
dataProviderStub = MockRepository.GenerateStub<IDataProvider>();
systemUnderTest = new PollCommand(timerStub, dataProviderStub);
// Act
systemUnderTest.StartPoll();
// Now execute the timer actions on
// the current thread.
timerStub.TickSeconds(3);
// Assert
dataProviderStub.AssertWasCalled(x=>x.Retrieve(),y=>y.Repeat.Times(3));
}
</pre>
<br />
Advantages:<br />
<ul>
<li>We are executing the <span style="font-family: "Courier New",Courier,monospace;">DoAsync()</span> method in our test.</li>
<li>Our multi-threading code can still use directly the concurrency methods of the .NET Framework Class Library like <span style="font-family: "Courier New",Courier,monospace;">Task.Factory.StartNew()</span> </li>
</ul>
Disadvantages:<br />
<ul>
<li>We need to prepare our code to inject the thread starting object. </li>
</ul>
See also my <a href="http://msdn.microsoft.com/en-us/magazine/dn818494.aspx">MSDN Magazine article</a> for general remarks about unit testing multithreaded code.
Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com1tag:blogger.com,1999:blog-1084762708281241901.post-26771636349337512472013-12-29T17:19:00.000+01:002014-11-03T23:00:52.834+01:00Unit testing c# code which starts new threads via tasksUnit testing multithreaded code seems sometimes impossible. We expect Unit Tests to run fast and to deliver predictable results. Tests which are executing code that spawns new threads are very often slow and fragile. These tests are not Unit Tests. Unit Tests are tests running our code in isolation from other parts of the system. Another part of the system are the classes providing access to the operating system multithreading capabilities. We use these classes to start new threads.<br />
To test the functional part of our code with unit tests we have to exclude the concurrency and synchronization aspects. These aspects are system-wide concerns and have to be tested later separately with integration tests. Integration tests can for example put the system under load to uncover synchronisation problems between multiple threads.<br />
But first we have to assure that the functional part of our code works as expected. We have to equip our code to be able to isolate the concurrency and synchronization aspects. Then we can write Unit Tests which are executing our functionality on the same thread as the unit test.<br />
So for Unit Tests in conjunction with multithreaded code we can summarize: <br />
<ul>
<li>Multithreaded code has to be equipped for isolating concurrency and synchronization aspects from functional aspects. </li>
<li>Unit Tests can only test the functional aspect of multithreaded code. They can not test concurrency and synchronization aspects of the code, because these are concerns outreaching a single unit.</li>
</ul>
The jMock Team has described an brilliant approach for Java in the<a href="http://jmock.org/threads.html"> 'jMock Cookbook: Test Multithreaded Code'</a>. This concept can also be applied to C# code using Tasks of the .NET Framework Class Libarary. The default <span style="font-family: "Courier New",Courier,monospace;">TaskScheduler</span> can be replaced with our own implementation called <span style="font-family: "Courier New",Courier,monospace;">DeterministicTaskScheduler</span> to test our code synchronously in a deterministic way. Unit tests are then able to run the tasks on their own thread:<br />
<br />
<pre class="brush:csharp">[Test]
public void ShouldUpdateTheStatusWhenDoAsync()
{
// Arrange
DeterministicTaskScheduler taskScheduler = new DeterministicTaskScheduler();
SystemUnderTest sut = new SystemUnderTest(taskScheduler);
Assert.AreEqual("Nothing done", sut.Status);
// Act
sut.DoAsync(); // starts a new task and returns immediately
Assert.AreEqual("Starting task", sut.Status);
// Now execute the new task
taskScheduler.RunTasksUntilIdle();
// Assert
Assert.AreEqual("Task done", sut.Status);
}
</pre>
<br />
Our code which starts a new task has to provide dependency injection capability for the TaskScheduler. We start a new task in <span style="font-family: "Courier New",Courier,monospace;">DoAsync()</span> via <span style="font-family: "Courier New",Courier,monospace;">Task.Factory.StartNew()</span>:
<br />
<pre class="brush:csharp">public class SystemUnderTest
{
private string status;
private TaskScheduler taskScheduler;
public SystemUnderTest(TaskScheduler taskScheduler)
{
status = "Nothing done";
this.taskScheduler = taskScheduler;
}
public string Status {get { return status;}}
public void DoAsync()
{
status = "Starting task";
Task.Factory.StartNew(
DoWork1,
new CancellationToken(),
TaskCreationOptions.None,
taskScheduler);
}
private void DoWork1()
{
// Do some work here
status = "Task done";
}
}</pre>
<br />
The <a href="https://gist.github.com/anonymous/8172108">DeterministicTaskScheduler</a> to be used in unit tests:
<br />
<pre class="brush:csharp"> /// <summary>
/// TaskScheduker for executing tasks on the same thread that calls RunTasksUntilIdle() or RunPendingTasks()
/// </summary>
public class DeterministicTaskScheduler : TaskScheduler
{
private List<Task> scheduledTasks = new List<Task>();
#region TaskScheduler methods
protected override void QueueTask(Task task)
{
scheduledTasks.Add(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
scheduledTasks.Add(task);
return false;
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return scheduledTasks;
}
public override int MaximumConcurrencyLevel { get { return 1; } }
#endregion
/// <summary>
/// Executes the scheduled Tasks synchronously on the current thread.
/// If those tasks schedule new tasks they will also be executed
/// until no pending tasks are left.
/// </summary>
public void RunTasksUntilIdle()
{
while (scheduledTasks.Any())
{
this.RunPendingTasks();
}
}
/// <summary>
/// Executes the scheduled Tasks synchronously on the current thread.
/// If those tasks schedule new tasks they will only be executed
/// with the next call to RunTasksUntilIdle() or RunPendingTasks().
/// </summary>
public void RunPendingTasks()
{
foreach (var task in scheduledTasks.ToArray())
{
this.TryExecuteTask(task);
scheduledTasks.Remove(task);
}
}
}
</pre>
<br />
In the client production code we can inject a real TaskScheduler from the current context to our class:
<br />
<pre class="brush:csharp">SystemUnderTest sut = new SystemUnderTest(
TaskScheduler.FromCurrentSynchronizationContext());
sut.DoAsync();
</pre>
<br />
See also my <a href="http://msdn.microsoft.com/en-us/magazine/dn818494.aspx">MSDN Magazine article</a> for general remarks about unit testing multithreaded code.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com3tag:blogger.com,1999:blog-1084762708281241901.post-86343516382645083072013-09-15T15:23:00.000+02:002013-09-15T15:37:27.922+02:00Example for a responsive console application with async/await vs threadsThere are mainly two reasons for using asynchronous programming:<br />
<ol>
<li>Utilize your CPU cores by parallelizing CPU intensive work.</li>
<li>Keep your application responsive while long running activities are in progress. These activities may be CPU intensive work or are waiting for a response from the web, lan or database (IO bound work) </li>
</ol>
Responsiveness is not only required for applications with an user interface but also for background services and applications. Background services should answer additional request even when they are currently busy with something else. On a user interface a user wants to at least be able to cancel a long running activity.
<br />
<br />
The following simple example demonstrate asynchronous programming with .NET 4.5 and async/await with an console application. The two long running activities (DoAction1() and DoAction2()) with CPU bound work are executed in parallel. The user can exit the application even before the computation and printing of the result has finished:
<br />
<pre class="brush:csharp">class Program
{
static void Main()
{
var program = new Program();
program.PrintResultAsync();
Console.WriteLine("Press <return> to exit ...");
Console.ReadLine();
}
public int DoAction1()
{
int result = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Action1 "+ result);
Thread.Sleep(250);
result++;
}
return result;
}
public int DoAction2()
{
int result = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Action2 " + result);
Thread.Sleep(250);
result--;
}
return result;
}
public async void PrintResultAsync()
{
Tuple<int, int> r = await ComputeResultAsync();
Console.WriteLine("Result " + r.Item1 + " + " + r.Item2 + " = " + (r.Item1 + r.Item2));
}
private async Task<Tuple<int, int>> ComputeResultAsync()
{
var t1 = Task<int>.Factory.StartNew(this.DoAction1);
var t2 = Task<int>.Factory.StartNew(this.DoAction2);
return new Tuple<int, int>(await t1, await t2);
}
}</pre>
<br />
The application has the output on the console below:<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdaax5T_q49x6sUDfAbODFo_EO4u6mC1qRs9yw1z4ak_pC35R9jSBbQ2oTQEvph7eusEIZoEsk6e2tQNzAZybXzXd6uifAzSFPDkqcGnLUOv4LDQcHGrDKBC9B4GRDTzImxNFS0y8FYts/s1600/ScreenshotConsoleAsyncSmall.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdaax5T_q49x6sUDfAbODFo_EO4u6mC1qRs9yw1z4ak_pC35R9jSBbQ2oTQEvph7eusEIZoEsk6e2tQNzAZybXzXd6uifAzSFPDkqcGnLUOv4LDQcHGrDKBC9B4GRDTzImxNFS0y8FYts/s320/ScreenshotConsoleAsyncSmall.png" /></a></div>
We can compare the previous async/await implementation with an equal implementation using plain threads. The thread based implementation is much longer and requires more overhead like additional member variables:
<br />
<pre class="brush:csharp">class Program
{
static void Main()
{
var program = new Program();
program.PrintResultWithThreads();
Console.WriteLine("Press <return> to exit ...");
Console.ReadLine();
}
public int DoAction1()
{
int result = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Action1 "+ result);
Thread.Sleep(250);
result++;
}
return result;
}
public int DoAction2()
{
int result = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Action2 " + result);
Thread.Sleep(250);
result--;
}
return result;
}
private int r1;
private int r2;
private ManualResetEvent e1 = new ManualResetEvent(false);
private ManualResetEvent e2 = new ManualResetEvent(false);
private WaitHandle[] manualEvents;
public void PrintResultWithThreads()
{
var printThread = new Thread(
() =>
{
e1 = new ManualResetEvent(false);
e2 = new ManualResetEvent(false);
manualEvents = new WaitHandle[] { e1, e2 };
ComputeResultsWithThreads();
WaitHandle.WaitAll(manualEvents);
Console.WriteLine("Result: " + r1 + " + " + r2 + " = " + (r1 + r2));
});
printThread.IsBackground = true;
printThread.Start();
}
private void ComputeResultsWithThreads()
{
var t1 = new Thread(
() =>
{
this.r1 = this.DoAction1();
this.e1.Set();
});
t1.IsBackground = true;
t1.Start();
var t2 = new Thread(
() =>
{
this.r2 = this.DoAction2();
this.e2.Set();
});
t2.IsBackground = true;
t2.Start();
}
}
</pre>
Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-9860801265478929732013-01-13T17:25:00.000+01:002013-01-13T17:25:09.115+01:00Introducing Continuous Integration: A Success StoryIn his book “The Clean Coder” Robert C. Martin tells several anecdotes from his professional live as a software developer to explain the attitude of a professional developer. That reminds me of a story when I started my current job.<br />
It was around 2009 when I started to work in an organization with seven software development teams each with the size of approximately ten people. The teams delivered every two month new software versions which are then manually integrated to a running system on a medical device hardware. The integration took around additional four to six weeks. I couldn't believe that software was created with this “stone age” process. In the worst case the developers got feedback for their features from the fully integrated system only after three month. Oh my good, why do I started to work there? I talked to my boss about my concerns and he admitted that we have to change something. So I was appointed as a project manager. The core project team had two members: Matt, a very experienced software consultant and me.<br />
We called the project “DailyBuild”. So our goal was to speed up the integration cycle time from ninety days to one. Yes, there where a lot of obstacles on our way. For example the teams used different source code control systems, we perceived the number of used build scripting tools as nearly infinite and the total software build time was about eight hours. Many problems we had to solve were related to the organizational structure of the development department. And of course if you want to change the way of working of people, a lot of them say: “Why should we change, we have always worked like this”. The only good thing was that I knew all the time that the project could not fail. I knew that the benefits would be overwhelming. The agile movement was already around several years and thousands of software teams had already adopted Continuous Integration.<br />
<br />
After 4 month we had the first successful automated build including a simple smoke test of the integrated system on a virtual machine. It took some more weeks to finish things. Today, no one in the development department can imagine to work any more without the “DailyBuild” process in place. Yes we made it!Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-75311157737565892572012-11-04T16:57:00.000+01:002012-11-16T22:42:28.326+01:00Lerning Perl with TDD and Unit TestsAs an absolute beginner to the language I needed to write my first Perl script. As a big fan of Test-Driven Development (TDD) I thought it would be a good idea to start with a test when doing the first Perl program. And it worked really nice. This post should be a simple step-by-step tutorial for Perl beginners who want to write simple Unit Tests for Perl. I will use my first Perl script as an example.<br />
<br />
<h2>
The Example: A ClearCase trigger</h2>
To customize the behaviour of ClearCase you have to write Perl scripts
which can be associated with any ClearCase command as a so called
ClearCase trigger (see <a href="http://www.ibm.com/developerworks/rational/library/4311.html">IBM Rational ClearCase: The ten best triggers</a>). For my example, I needed a trigger that updates a FitNesse Wiki page (the file name is always "content.txt") when it is checked-in to ClearCase. If the file contains a string like "$Revision: \main\MAINLINE_SQE\3 $" the Perl script should update the version information. That's it. <br />
<br />
<h2>
Step-by-Step Tutorial</h2>
<br />
<ol>
<li>Install Perl.</li>
<li>Create a folder "PerlScripts" for the new Perl scripts. We will have two files in this folder: "CiVersionFitnesseTrigger.pl" is the Perl script for the trigger. "CiVersionFitnesseTriggerTests.pl" is the Perl script for the corresponding Unit Tests. </li>
<li>Download the <a href="http://search.cpan.org/~mschwern/Test-Simple-0.98/lib/Test/Simple.pm">Test::Simple</a> Perl module. Unpack the gz archive. We will only need the file "Simple.pm" from the folder "lib/Test". Create a folder "Test" as sub folder of our "PerlScripts" folder. Copy the file "Simple.pm" to this "Test" folder.</li>
</ol>
We start writing our first test in "CiVersionFitnesseTriggerTests.pl":
<br />
<pre class="brush:perl">use Test::Simple tests => 1;
# System under test
require 'CiVersionFitnesseTrigger.pl';
# Testing is_fitnesse_wiki_page() method
ok(FitTrigger::is_fitnesse_wiki_page('content.txt'), 'content.txt is page');
</pre>
<br />
We start defining an empty sub routine and an empty main routine in "CiVersionFitnesseTrigger.pl":
<br />
<pre class="brush:perl">package FitTrigger;
sub is_fitnesse_wiki_page {
return 0;
}
#
# Main method
#
1;
</pre>
We can now run the first unit test and see it failing:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhf5VifC5-uYCZQCtJhEc10efbEuti8Yomfb3c_4LbAh4BypLx3sUc09UDN3yPUv7i-er3a61Q64Sfbtx10tkN_D1uKeHFdL9N9nCElhfhdTWw5WjLQ7_EMgmKdrNe_aCo6yJNHY4b6KE/s1600/Console01.png" imageanchor="1" style=""><img border="0" height="202" width="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhf5VifC5-uYCZQCtJhEc10efbEuti8Yomfb3c_4LbAh4BypLx3sUc09UDN3yPUv7i-er3a61Q64Sfbtx10tkN_D1uKeHFdL9N9nCElhfhdTWw5WjLQ7_EMgmKdrNe_aCo6yJNHY4b6KE/s400/Console01.png" /></a>
<br />
Now we have the infrastructure to start implementation. We fix the first failing test:
<pre class="brush:perl">package FitTrigger;
sub is_fitnesse_wiki_page {
my ($file_name) = @_;
return $file_name =~ m/^(.*\\)?content\.txt$/
}
#
# Main method
#
1;
</pre>
Now run the unit test again and it succeeds:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdLN_5Z-tPqjzUUJXPde088icpVUDoZ-J2xg3_8U_fcRWVhzMRnOY1s-AJPvb9_ytcLqoW6WD00sN6yfNXD4a3ai785OKYk_RiUMLcyDTpp-_IzW9NZwv2NqZr_YuU9LqKM-8uriNncbQ/s1600/Console02.png" imageanchor="1" style=""><img border="0" height="202" width="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdLN_5Z-tPqjzUUJXPde088icpVUDoZ-J2xg3_8U_fcRWVhzMRnOY1s-AJPvb9_ytcLqoW6WD00sN6yfNXD4a3ai785OKYk_RiUMLcyDTpp-_IzW9NZwv2NqZr_YuU9LqKM-8uriNncbQ/s400/Console02.png" /></a>
<br />
We continue the cycle of writing new unit tests and implementing the script step by step. In the end we have 12 unit tests and 1 integration test:
<pre class="brush:perl">use Test::Simple tests => 13;
# System under test
require 'CiVersionFitnesseTrigger.pl';
# Testing is_fitnesse_wiki_page() method
ok(FitTrigger::is_fitnesse_wiki_page('content.txt'), 'content.txt is page');
ok(FitTrigger::is_fitnesse_wiki_page('c:\content.txt'), 'c:\content.txt is page');
ok(FitTrigger::is_fitnesse_wiki_page('..\content.txt') , '..\content.txt is page');
ok(FitTrigger::is_fitnesse_wiki_page('c:\temp\content.txt'), 'c:\temp\content.txt is page');
ok(!FitTrigger::is_fitnesse_wiki_page('content.txt.old') , 'content.txt.old is not a page');
ok(!FitTrigger::is_fitnesse_wiki_page('somecontent.txt') , 'somecontent.txt is not a page');
ok(!FitTrigger::is_fitnesse_wiki_page('content.txt\something.txt') , 'content.txt\something.txt is not a page');
# Testing getTempFolder() method
my $tmpFolder = FitTrigger::get_temp_folder();
ok(defined($tmpFolder) && $tmpFolder ne '' && length($tmpFolder) > 1 , 'temporary folder not empty');
# Testing getTempFile() method
my $tmpFile = FitTrigger::get_temp_file();
ok(defined($tmpFile) && $tmpFile ne '' && length($tmpFile) > 1 , 'temporary file not empty');
# Testing update_revision_in_target() method
my $testFile = "$tmpFolder\\test.txt";
my $targetFile = "$tmpFolder\\target.txt";
open("TESTFILE", ">$testFile") ||
&error("Could not open test File $testFile for writing");
print TESTFILE "hallo1\nhallo2\n\$Revision: VERSION_ZZZ \$\n";
close TESTFILE;
my $newVersion = 'VERSION_111';
FitTrigger::update_revision_in_target($testFile,$targetFile,$newVersion);
open(F,"$targetFile");
my @list = <F>;
my $content=join('',@list);
close F;
my $expectedContent = "hallo1\nhallo2\n\$Revision: VERSION_111 \$\n";
ok($content eq $expectedContent, 'version was updated in target file');
# Testing overwrite_file() method
FitTrigger::overwrite_file($targetFile,$testFile);
open(F2,"$testFile");
@list=<F2>;
my $newContent =join('',@list);
close F2;
ok($newContent eq $expectedContent, 'file was overwritten with a modified file');
ok(! -e $targetFile, 'modified file is deleted');
# Testing main() method
$testFile = "$tmpFolder\\content.txt";
open("TESTFILE", ">$testFile") ||
&error("Could not open test File $testFile for writing");
print TESTFILE "hallo1\nhallo2\n\$Revision: VERSION_ZZZ \$\n";
close TESTFILE;
$ENV{CLEARCASE_PN}=$testFile;
$ENV{CLEARCASE_ID_STR}='VERSION_888';
system ("perl CiVersionFitnesseTrigger.pl");
my $expectedContentMain = "hallo1\nhallo2\n\$Revision: VERSION_888 \$\n";
open(F3,"$testFile");
@list=<F3>;
my $newContentMain =join('',@list);
close F3;
ok($newContentMain eq $expectedContentMain, 'perl script has updated content.txt');
</pre>
<br />
The complete implementation in "CiVersionFitnesseTrigger.pl" looks like:
<pre class="brush:perl">package FitTrigger;
sub is_fitnesse_wiki_page {
my ($file_name) = @_;
return $file_name =~ m/^(.*\\)?content\.txt$/
}
sub get_temp_folder {
my $tmp_folder = $ENV{TMP};
$tmp_folder = $ENV{TEMP} unless ($tmp_folder);
$tmp_folder = "/tmp" unless ($tmp_folder);
return $tmp_folder;
}
sub get_temp_file {
my $tmp_folder = get_temp_folder();
return "$tmpFolder\\ccTriggerTmp.$$";
}
sub update_revision_in_target {
my $source = @_[0];
my $target = @_[1];
my $revision = @_[2];
open("SOURCE", "$source") ||
&error("Could not open source file $source for reading");
open("TARGET", ">$target") ||
&error("Could not open target file $target for reading");
while (<SOURCE>)
{
if (/\$Revision:?.*\$/) {
s/\$Revision:?.*\$/\$Revision: $revision \$/;
}
print TARGET;
}
close SOURCE;
close TARGET;
}
sub overwrite_file {
my $source = @_[0];
my $target = @_[1];
open (SOURCE, "$source") ||
&error ("Could not open source file $source for reading");
open (TARGET, ">$target") ||
&error ("Could not open target file $target for writing");
while(<SOURCE>) {
print TARGET;
}
close(SOURCE);
close(TARGET);
unlink($source);
}
sub error {
my ($message) = @_;
die ($message."\nUnable to continue checkin ...\n");
}
#
# Main method
#
# Summary:
# If the name of the checkin file is ‘content.txt’ then search in the content of the file for a string like
# „$Revision: \main\MAINLINE_22_WIPID\4 $“. This string will then be replaced
# with e.g. „$Revision: \main\MAINLINE_22_WIPID\5 $“.
my $check_in_file = $ENV{'CLEARCASE_PN'};
my $revision = $ENV{'CLEARCASE_ID_STR'};
if(is_fitnesse_wiki_page($check_in_file)) {
my $targetFile = get_temp_file();
update_revision_in_target($check_in_file,$targetFile,$revision);
overwrite_file($targetFile,$check_in_file);
}
1;
</pre>
Running the tests:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghhGwHrXqVqnxU_PjyjR9ARfprWJqDtrju6K57P7SH3pZJvxRm58d4voNER6rH_iGly1lA0noTy5QTAfrO9NDqVAb_cfWSVKa-0DrXVv2CE-eydBLCbo4JFVdNUb4bS8iJ_XcuGQcIkzk/s1600/Console03.png" imageanchor="1" style=""><img border="0" height="202" width="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghhGwHrXqVqnxU_PjyjR9ARfprWJqDtrju6K57P7SH3pZJvxRm58d4voNER6rH_iGly1lA0noTy5QTAfrO9NDqVAb_cfWSVKa-0DrXVv2CE-eydBLCbo4JFVdNUb4bS8iJ_XcuGQcIkzk/s400/Console03.png" /></a>
<br />
<br />Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com1tag:blogger.com,1999:blog-1084762708281241901.post-85414462583047286722012-04-22T14:57:00.006+02:002012-04-23T22:16:03.542+02:00Advantages of Fitnesse over traditional testing toolsCurrently I'm part of a team that tries to introduce test automation to our organization. We are developing products for the healthcare sector with relatively long release cycles due to high regulatory requirements. These long release cycles are resulting mainly because of high manual test efforts and missing test automation.
There were some discussions which tools to use for test automation. Two main possibilities are available:
<ul><li>Traditional commercial, heavyweight, GUI-based, record and replay tools like HP QuickTest Professional, IBM Rational Robot, QF-Test or Borland SilkTest.</li><li>Agile Acceptance test tools like Fit/<a href="http://fitnesse.org/">Fitnesse</a>.</li></ul>
<p/>
In a pilot project we found some advantages of Fitnesse over traditional commercial testing tools:
<h3>No Licence costs for Fitnesse</h3>
Ok, in a big company it's not a big issues to spend some money for commercial tools, but even then you will not buy licences for every machine and every employee. Fitnesse we use on every developer machine, on every tester laptop, on every machine in the test lab, on laptops for presentations in meetings. You can use it on every machine you want without filling order forms and waiting weeks for completion of the order process. So the use of Fitnesse is not limited to the test specialist but instead we can use it cross-functional for application specialists, testers, developers and software architects.
<p/>
<h3>Simple Installation of Fitnesse</h3>
Fitnesse can be brought to a machine simply by copying a folder with its subfolders. Or you can run it from an USB stick, which is quite practical for tests on systems wich are not connected to the corporate network.
<p/>
<h3>Test-First approach with Fitnesse</h3>
It is a natural approach to write down the test specification before or during the development of the software, because developers need the input to provide test fixtures for connecting the Fitnesse tests with the production code.
<p/>
Please refer to Elisabeth Hendrickson's blog for similar and more advantages:
<a href="http://testobsessed.com/blog/2008/04/29/agile-friendly-test-automation-toolsframeworks/">Agile-Friendly Test Automation Tools/Frameworks</a>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-24435338551136386692012-02-27T21:20:00.014+01:002012-03-01T21:42:47.351+01:00Mocking Best PracticesWhen writing unit tests you have to use mocks or stubs for dependant objects. Very often it is convenient to use a mocking library (like <a href="http://hibernatingrhinos.com/open-source/rhino-mocks">RhinoMocks</a> for .NET or <a href="http://www.jmock.org/">jMock</a> for Java). Just using a mocking library does not guarantee to get readable and maintainable unit tests. It make sense to have a set of rules which are guiding developers when writing unit tests with mock objects. I compiled a list of such best practices for mock objects ("mocking" rules). I use the term <a href="http://xunitpatterns.com/Mock%20Object.html">mock object</a> for a objects verifying expectations about calls to themselves. <a href="http://xunitpatterns.com/Test%20Stub.html">Test stubs</a> are only used for feeding inputs into the system under test.
<p>
<span style="font-weight: bold;">Rule 1:</span> Try to avoid using mock objects and prefer state verification over behaviour verification if it is possible.</p><p>If you can verify the outcome of an method by checking the return value or by checking the state of the system under test, this is the preferable method, because it is simpler and makes your test more independent from the implementation details. You may need test stubs to feed indirect inputs into the system under test.
</p><p>
<span style="font-weight: bold;">Rule 2:</span> Apply the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a> („no train wrecks”) to your code you want to unit test as much as possible.</p><p>Testing code like "<span style="font-size:85%;"><span style="font-family:courier new;"><span style="font-size:85%;">employee.GetDepartment().GetManager().GetOffice().GetAddress().GetZip()</span></span></span>" is much harder than "<span style="font-size:85%;"><span style="font-family:courier new;">employee.GetManagersOfficeZipCode()</span>".</span></p><p>Avoiding "train wrecks" reduces the number of mocks and stubs you need and therefore improves readability and maintainability for your tests. </p><p>
<span style="font-weight: bold;">Rule 3:</span> Use a minimum number of mock objects per test, preferable is only one mock object.</p><p>Concentrate on one aspect per test. A reader can identify the most important part more easily. In one test you may check the call to <a href="http://xunitpatterns.com/DOC.html">one depended-on component (DOC)</a> and in another test you will check another DOC. You may need additional test stubs to feed indirect inputs into the system under test.
</p><p>
<span style="font-weight: bold;">Rule 4:</span> Define a minimum number of expectations as possible.</p><p>It’s easier for the reader to see what is important. Tests are less brittle when code changes. Test <span style="font-style: italic;">what</span> code does, not <span style="font-style: italic;">how</span>.
</p><p>
<span style="font-weight: bold;">Rule 5:</span> Use <a href="http://martinfowler.com/bliki/CommandQuerySeparation.html">Command-Query Separation (Side-Effect-Free Functions)</a> for your code. Don't define expectations on mock objects for queries, only for commands.</p><p>Divide all object's methods of your code into two sharply separated categories:
</p><ul><li>Queries: Return a result and do not change the observable state of the system (are free of side effects).</li><li>Commands: Change the state of a system but do not return a value.</li></ul>Queries deliver input for tests, commands are output. Only check the output (<span style="font-style: italic;">what</span>)<p></p><p>
<span style="font-weight: bold;">Rule 6:</span> At the borderline between your own code towards foreign code, it may be wise to not stub or mock the foreign code directly.</p><p>Very often it is better to create an own interface and implement a small layer of adapter code. Test this small layer with integration tests including the foreign code. It is much easier then to stub or mock your own adapter interface when you test your other own code. Examples for foreign code are database access code (like ADO.NET, JDBC in Java, Hibernate, NHibernate), active directory access, network access, and so on.
</p><p>
<span style="font-weight: bold;">References:</span>
</p><ul><li>Martin Fowler: <a href="http://martinfowler.com/articles/mocksArentStubs.html">"Mocks Aren't Stubs"</a></li><li>Jeremy Miller: <a href="http://codebetter.com/jeremymiller/2006/01/10/best-and-worst-practices-for-mock-objects/">"Best and Worst Practices for Mock Objects"</a></li><li>Steve Freeman, Nat Pryce: <a href="http://www.growing-object-oriented-software.com/">"Growing Object-Oriented Software, Guided by Tests"</a></li><li>Roy Osherove: <a href="http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&qid=1330375462&sr=8-1">"Art of Unit Testing"</a></li></ul><p></p>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-77322673954097940362011-12-21T16:52:00.022+01:002012-01-17T21:03:16.083+01:00Testing Java Console ApplicationsCurrently 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 <a href="http://en.wikipedia.org/wiki/Nine_Men%27s_Morris">Nine Men's Morris</a> 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.
<p/>
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.
<p/>
I started with an acceptance test. I choose to implement it with JUnit, but <a href="http://fitnesse.org/">Fitnesse</a> tool would have been an alternative.
<pre class="brush:java">
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");
}
}
</pre>
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 <em>System.out</em> and reads from the console via <em>System.in</em>:
<pre class="brush:java">
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>0 && !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());
}
}
</pre>
The <em>Console.main()</em> method set ups and starts the console application:
<pre class="brush:java">
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();
}
</pre>
When we develop the <em>ConsoleGameUI</em> 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:
<pre class="brush:java">
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();
}
...
}
</pre>
In the <em>ConsoleGameUI</em> class we use <em>System.out</em> and <em>System.in</em>:
<pre class="brush:java">
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;
}
...
}
</pre>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com7tag:blogger.com,1999:blog-1084762708281241901.post-61673454894295546842011-02-25T17:04:00.016+01:002014-01-04T19:24:44.183+01:00Rhino Mocks Arrange / Act / Assert (AAA) Syntax Quick ReferenceRecently 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 or an API documentation for this syntax style. Based on Ayende's article <a href="http://www.ayende.com/wiki/Rhino+Mocks+3.5.ashx">Rhino Mocks 3.5</a> and the <a href="http://www.ayende.com/wiki/GetFile.aspx?File=Rhino+Mocks+3.3+Quick+Reference.pdf">Rhino Mocks 3.3 Quick Reference</a> I created a new document with code examples:
<p></p><p></p>
<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&pid=explorer&chrome=true&srcid=0By6Nqi32xrTtMGQxMzc1MWItOTU5Yy00YmMzLTlhNjgtYWIxZmE4ZTUzZWI2&hl=en_US">Rhino Mocks AAA Syntax Quick Reference on Google Docs</a>
<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;">Rhino Mocks AAA Syntax Quick Reference on Scribd</a> <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%"> <param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"> <param name="wmode" value="opaque"> <param name="bgcolor" value="#ffffff"> <param name="allowFullScreen" value="true"> <param name="allowScriptAccess" value="always"> <param name="FlashVars" value="document_id=49587062&access_key=key-1s0hguy3hybq5jpxhu73&page=1&viewMode=list"> <embed id="doc_635178337297290" name="doc_635178337297290" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=49587062&access_key=key-1s0hguy3hybq5jpxhu73&page=1&viewMode=list" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" bgcolor="#ffffff" height="600" width="100%"></embed> </object>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com4tag:blogger.com,1999:blog-1084762708281241901.post-50099083490708304892010-11-04T13:59:00.006+01:002010-11-04T14:25:47.766+01:00'Design By Contract' MetricsWe 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.
<p></p>
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:
<ol><li> Absolut number of contract assertions per component</li><li> Average number of contract assertions per class per component</li></ol>
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.
<p></p>
The metrics are published on a regular basis and serve as a means for motivation.
<p></p>
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.
<p></p>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-16402921665432914762010-10-28T23:04:00.010+02:002010-11-04T13:15:15.801+01:00Example for parsing C# code with the NRefactory libraryNRefactory is part of the open source IDE <a href="http://www.icsharpcode.net/opensource/sd/">SharpDevelop</a> 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.
</p>
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.
</p>
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 <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">Code Contracts</a>.
<pre class="brush:csharp">
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 <= 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);
}
}
}
</pre>
To traverse the AST we can use the <span style="font-style:italic;">Visitor</span> pattern (see <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0201633612">[Gamma et.al:Design Patterns]</a>. 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:
<pre class="brush:csharp">
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) && !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 &&
identifierExpression.Identifier == "Contract" &&
(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
}
}
</pre>
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:
<pre class="brush:csharp">
...
// 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)");
...
</pre>
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:
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgI6OdoVBEmbmndNKzvkVm4T1uCcMEjxBJ0Stssx8jKepmEEgY8ralXoWPSz7FfdtIA1C6h3Xbe8WIwCDdJfxpZ39b2WYhGdYjrKtgCjns6r25mKoQfqbFfcLEu3SORa3MC2oFd8kHKSq0/s1600/NRefactoryDemoScreenshot.png"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 242px; height: 320px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgI6OdoVBEmbmndNKzvkVm4T1uCcMEjxBJ0Stssx8jKepmEEgY8ralXoWPSz7FfdtIA1C6h3Xbe8WIwCDdJfxpZ39b2WYhGdYjrKtgCjns6r25mKoQfqbFfcLEu3SORa3MC2oFd8kHKSq0/s320/NRefactoryDemoScreenshot.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5533572057950449250" /></a>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com1tag:blogger.com,1999:blog-1084762708281241901.post-13467518659801633352009-11-29T20:27:00.021+01:002011-12-27T15:44:06.112+01:00Stubs vs Mocks with Rhino MocksRecently I was asked: "What is the difference between Stubs and Mocks?" Martin Fowler has written a good article about that topic <a href="http://martinfowler.com/articles/mocksArentStubs.html">"Mocks Aren't Stubs"</a>. Also in the <a href="http://www.ayende.com/Wiki/Rhino+Mocks+3.5.ashx">Rhino Mocks Wiki</a> there is is comprehensive explanation.
<p/>
Besides the theoretical aspect you have to decide whether to use<p/>
<span style="font-weight: bold;">MockRepository.GenerateMock</span> or <p/>
<span style="font-weight: bold;">MockRepository.GenerateStub</span><p/>
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:
<pre class="brush:csharp">
[Test]
[(typeof(ExpectationViolationException))]
public void VerifyAllExpectationsWithExpectMethodOnMock()
{
IList listMock = MockRepository.GenerateMock<IList>();
listMock.Expect(x => x.Count).Return(10);
listMock.VerifyAllExpectations();
}
[Test]
public void VerifyAllExpectationsWithExpectMethodOnStub()
{
IList listStub = MockRepository.GenerateStub<IList>();
listStub.Expect(x => x.Count).Return(10);
listStub.VerifyAllExpectations();
}
[Test]
public void VerifyAllExpectationsWithStubMethodOnMock()
{
IList listMock = MockRepository.GenerateMock<IList>();
listMock.Stub(x => x.Count).Return(10);
listMock.VerifyAllExpectations();
}
[Test]
public void VerifyAllExpectationsWithStubMethodOnStub()
{
IList listStub = MockRepository.GenerateStub<IList>();
listStub.Stub(x => x.Count).Return(10);
listStub.VerifyAllExpectations();
}
[Test]
[ExpectedException(typeof(ExpectationViolationException))]
public void AssertWasCalledWithMock()
{
IList listMock = MockRepository.GenerateMock<IList>();
listMock.AssertWasCalled(x => { int temp = x.Count; });
}
[Test]
[ExpectedException(typeof(ExpectationViolationException))]
public void AssertWasCalledWithStub()
{
IList listStub = MockRepository.GenerateStub<IList>();
listStub.AssertWasCalled(x => { int temp = x.Count; });
}
</pre>
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:
<ol><li><span style="font-weight: bold;">GenerateMock</span> with <span style="font-weight: bold;">Expect(...)</span> and <span style="font-weight: bold;">VerifyAllExpectations()</span></li><li><span style="font-weight: bold;">GenerateMock</span>/<span style="font-weight: bold;">GenerateStub</span> with <span style="font-weight: bold;">AssertWasCalled(...)</span></li></ol>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-45318373563667706752009-10-12T23:26:00.004+02:002009-10-12T23:39:13.924+02:00LightContracts is a simple, small and lightweight library supporting 'Design by Contract'Recently I created a project on Codeplex.com. It is called <a href="http://lightcontracts.codeplex.com/">LightContracts</a> 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 <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">Code Contracts</a> projects would be included as part of .Net 4.0.
<p/>
<span style="font-weight: bold;">So why should I use LightContracts?</span>
<p/>
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. <a href="http://lightcontracts.codeplex.com/">LightContracts</a> 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.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com1tag:blogger.com,1999:blog-1084762708281241901.post-28574374491365746292009-02-11T21:55:00.020+01:002010-10-24T14:07:24.415+02:00What is Design by Contract?<p>This is the first article in a series which I started after I reasoned about <a href="http://svengrand.blogspot.com/2009/02/why-is-design-by-contract-not-common.html">"Why is Design by Contract not common practice in Software Enineering?"</a>.</p>
<p><span style="font-style: italic;">Design by Contract</span> 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. <span style="font-style: italic;">Design by Contract</span> 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.</p>
<p>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.</p>
<p>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:</p>
<pre class="brush:csharp">
public class Printers
{
private List<string> names;
public Printers()
{
names = new List<string>();
names.Add("printer1");
names.Add("printer2");
}
/// <summary>
/// List of printer names.
/// Assertion.Ensure(names != null,"Result is not null");
/// </summary>
public List<string> PrinterNames
{
get
{
Assertion.Ensure(names != null,"Result is not null");
return names;
}
}
/// <summary>
/// Remove a printer
/// Assertion.Require(PrinterNames().Count > 0,"There is at least one printer");
/// Assertion.Require(printerIndex >= 0,"printerIndex is not negative");
/// Assertion.Require(printerIndex lessThan PrinterNames().Count ,"printerIndex is in range");
/// </summary>
public void RemovePrinter(int printerIndex)
{
Assertion.Require(PrinterNames.Count > 0,"There is at least one printer");
Assertion.Require(printerIndex >= 0,"printerIndex is not negative");
Assertion.Require(printerIndex < PrinterNames.Count ,"printerIndex is in range");
names.RemoveAt(printerIndex);
}
...
}
</pre>
<p>For further information about <span style="font-style: italic;">Design by Contract</span> please refer to the <a href="http://archive.eiffel.com/doc/manuals/technology/contract/">Eiffel web site</a> or the book <a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0136291554">Object-Oriented Software Construction</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<p>In the next article I will try to answer the question: What are the benefits of <span style="font-style: italic;">Design by Contract</span>?</p>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-83700068498711869882009-02-04T14:35:00.007+01:002009-02-13T10:07:01.111+01:00Why is Design by Contract not common practice in Software EnineeringConcerned with a lot of source code reviews over the last years, I have recognized that <span style="font-style: italic;">Design by Contract</span> 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 <span style="font-style: italic;">Design by Contract</span>. Thinking about the reasons for programmers not to use <span style="font-style: italic;">Design by Contract</span> I made a list with questions they may have:
<ul><li><a href="http://svengrand.blogspot.com/2009/02/what-is-design-by-contract.html">What is <span style="font-style: italic;">Design by Contract</span>?</a>
</li><li>What are the benefits of <span style="font-style: italic;">Design by Contract</span>?</li><li>Do I need to use Eiffel as my programming language to apply <span style="font-style: italic;">Design by Contract?</span></li><li>Do I have to spend a lot of effort for <span style="font-style: italic;">Design by Contract</span>?</li><li>In which situations should I use <span style="font-style: italic;">Design by Contract</span>?</li><li>Does <span style="font-style: italic;">Design by Contract</span> conflict with other design and implementation techniques like TDD and DDD?</li></ul>If you have no or wrong answers for these questions you will probably not use <span style="font-style: italic;">Design by Contract</span> 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 <span style="font-style: italic;">Design by Contract </span>is an elegant technique to improve software quality.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com3tag:blogger.com,1999:blog-1084762708281241901.post-40832336933659451542009-01-15T23:50:00.009+01:002010-10-24T14:09:58.348+02:00Preconditions, Postconditions: Design by Contract for C#Bertrand Meyer has described a design technique called "Design by Contract" (DBC) in his book <a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0136291554">Object-Oriented Software Construction</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. 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):
<pre class="brush:csharp">
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);
}
}
</pre>
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:
<pre class="brush:csharp">
public class PrinterDescription
{
private XmlDocument printerXml;
/// <summary>
/// Load the descripton from a xml file
/// Assertion.RequireIsNotNull(printerDescriptionPath, "printerDescriptionPath");
/// Assertion.Require(File.Exists(printerDescriptionPath), "File printerDescriptionPath exists");
/// Assertion.Ensure(IsLoaded, "IsLoaded");
/// </summary>
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");
}
/// <summary>
/// Is the description loaded?
/// </summary>
public bool IsLoaded
{
get
{
return printerXml != null;
}
}
/// <summary>
/// Name of the printer
/// Assertion.Require(IsLoaded, "IsLoaded");
/// </summary>
public string Name
{
get
{
Assertion.Require(IsLoaded, "IsLoaded");
XPathNavigator nameNode = printerXml.CreateNavigator().SelectSingleNode("//PrinterName");
return nameNode.Value;
}
}
}
</pre>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com2tag:blogger.com,1999:blog-1084762708281241901.post-78043160194021667952008-12-18T00:00:00.017+01:002010-10-24T14:16:29.119+02:00Preconditions, Postconditions, Invariants : Design by Contract for Java #2Recently I wrote about how to apply <a href="http://svengrand.blogspot.com/2008/11/preconditions-postconditions-invariants.html">"Design by Contract" with Java</a>. I proposed to use the assert statement of java, in case you do not want to set up some external tools like <a href="http://www.contract4j.org/contract4j"> Contract4J</a>, <a href="http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-cooltools.html">iContract</a> or <a href="http://csd.informatik.uni-oldenburg.de/%7Ejass/">Jass</a>. After using the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assert</a> statement for a while I would recommend to use your own implementation of assertions instead like this:
<pre class="brush:java">
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");
}
}
}
</pre>
Why is the own implementation better than the assert statement?
<ol><li>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.</li><li>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,</li></ol>
You can find details about "Design by Contract" in the famous book <a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0136291554">Object-Oriented Software Construction</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> by Bertrand Meyer. <p/>
<iframe src="http://rcm.amazon.com/e/cm?t=whcodo-20&o=1&p=8&l=as1&asins=0136291554&fc1=000000&IS2=1<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-55250048224053819242008-12-15T10:58:00.006+01:002010-10-24T14:17:56.163+02:00Mocking an object with two interfacesCurrently 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.
<pre class="brush:java">
public class TextManager {
private IReader reader;
public void readAndWrite() {
String text = reader.read();
text = "*" + text + "*";
((IWriter)reader).write(text);
}
}
</pre>
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:
<pre class="brush:java">
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();
}
</pre>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-52523480587250578172008-11-27T21:40:00.038+01:002010-11-04T13:39:47.550+01:00Preconditions, Postconditions, Invariants : Design by Contract for JavaIn his famous book <a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0136291554">Object-Oriented Software Construction</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0136291554" alt="" style="border: medium none ! important; margin: 0px ! important; display: none;" border="0" width="1" height="1" /> 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<a href="http://java.sun.com/j2se/javadoc/"> javadoc</a> documentation.
<p>There are a lot of tools and framework which help you to apply DBC to your Java code. For example <a href="http://oval.sourceforge.net/index.html">OVal</a>,<a href="http://www.contract4j.org/contract4j"> Contract4J</a>, which are using AspectJ, <a href="http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-cooltools.html">iContract</a> or <a href="http://csd.informatik.uni-oldenburg.de/%7Ejass/">Jass</a>, which are using a preprocessor for Java.
</p><p>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 <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assert</a> 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":
</p>
<pre class="brush:java">
/**
* 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;
}
</pre>
So you can use "Design by Contract" effectively with three simple rules:<p></p><ul><li>Use the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assert</a> mechanism of Java to check preconditions, postconditions and invariants at runtime.</li><li>Describe each <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assert</a> with a string that starts either with "Precondition:", "Postcondition:" or "Invariant:" followed by the textual description of the assert expression.</li><li>Add each <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assert</a> description string to the <a href="http://java.sun.com/j2se/javadoc/">javadoc</a> comment of the method</li></ul>We can get a little more support, when we write our own pre- and postcondition class:
<pre class="brush:java">
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");
}
}
}
</pre>
Using this class instead of 'assert' has the advantage that we can't forget to switch on the runtime checking of the assertions with <span style="font-style: italic;">-enableassertions</span>. 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:
<pre class="brush:java">
/**
* 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;
}
</pre>
There is also an article <a href="http://java.sun.com/developer/technicalArticles/JavaLP/assertions/">"Using Assertions in Java Technology"</a> on the Sun Developer network.
See <a href="http://svengrand.blogspot.com/2008/12/preconditions-postconditions-invariants.html">"Preconditions, Postconditions, Invariants : Design by Contract for Java #2"</a> for further infos. <p>
<iframe src="http://rcm.amazon.com/e/cm?t=whcodo-20&o=1&p=8&l=as1&asins=0136291554&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width: 120px; height: 240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0"></iframe></p>Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com2tag:blogger.com,1999:blog-1084762708281241901.post-69066450381338450762008-10-28T20:26:00.008+01:002009-01-04T22:39:20.087+01:00CruiseControl, ClearCase and Dynamic ViewsWhen 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 <a href="http://www.amazon.com/gp/product/0321356993?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321356993">Kevin A. Lee: IBM Rational(R) ClearCase(R), Ant, and CruiseControl: The Java(TM) Developer's Guide to Accelerating and Automating the Build Process</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321356993" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. 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 <a href="http://wrapper.tanukisoftware.org/doc/english/index.html">Java Service Wrapper</a>. 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.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-22019912061427553342008-08-26T22:34:00.010+02:002009-01-04T22:41:25.937+01:00TDD and Layered ArchitectureI just read the blog post of Jeffrey Palermo about the <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-3/">Onion Architecture</a> (see also the similar pattern <a href="http://alistair.cockburn.us/index.php/Hexagonal_architecture">Hexagonal architecture</a>). Aspects of this patterns are used in an architecture our team defined for a healthcare information system.
<p/>
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.
<p/>
Eric Evans presented a pattern called Layered Architecture in his book <a href="http://www.amazon.com/gp/product/0321125215?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321125215">Domain-Driven Design: Tackling Complexity in the Heart of Software</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321125215" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. 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.
<p/>
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 <span style="font-style:italic;">pure unit tests</span> 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 <span style="font-style:italic;">pure unit tests</span>. 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 <span style="font-style:italic;">pure unit tests</span>. 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 <span style="font-style:italic;">database unit tests</span>. They are much slower than the <span style="font-style:italic;">pure unit tests</span>.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-91275560110738926022008-07-25T11:51:00.030+02:002010-10-24T14:23:44.242+02:00Configure CruiseControl LoggingIf you have problems to get your CruiseControl running you may want to see some more log output. For example when your < modificationset> 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 <span style="font-weight: bold;">log4j.properties</span> 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:
<pre class="brush:plain">
# 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
</pre>
Modify the <span style="font-weight: bold;">CruiseControl.bat</span> which starts the CruiseControl build loop.
Add the command line parameter "-Dlog4j.configuration=file:./log4j.properties"
to the call of the java application:
<pre class="brush:bash">
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 "< javac>") 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%
</pre>
With this setup you get more detailed output concerning the access towards the source code repository.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com1tag:blogger.com,1999:blog-1084762708281241901.post-55695014595915813672008-05-22T21:13:00.029+02:002009-01-15T23:17:09.481+01:00A New xUnit Test PatternInspired by the Gerard Meszaros book <a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0131495054">xUnit Test Patterns: Refactoring Test Code</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0131495054" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, I have written down a pattern, which I used already many times:
<h1>Own Library Interface</h1>
Also known as: 'Skin and Wrap the API' [<a href="http://www.amazon.com/gp/product/0131177052?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0131177052">Working Effectively with Legacy Code</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0131177052" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;"/>by Michael Feathers]
<p/>
<span style="font-style: italic;">How can we make a code testable, when the code depends on a library class, which can't be replaced by a 'Test Double'?</span>
<p/>
<span style="font-weight: bold;">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.</span>
<p/>
<div style="text-align: center;"><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJu7KhZb-UCIgp_gXkQBPxRxEVCkU7w05Mi6-hsw9Ct4k-MMzeailKk-r3EHXrrURYHhmQSi335ZmRb5kS7F8h0CcIMkA4Zx-bJ1PEbYhgibIBMoWuqgBqA8UG5kll32pA2MAEr4Evobs/s1600-h/Pattern.png"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJu7KhZb-UCIgp_gXkQBPxRxEVCkU7w05Mi6-hsw9Ct4k-MMzeailKk-r3EHXrrURYHhmQSi335ZmRb5kS7F8h0CcIMkA4Zx-bJ1PEbYhgibIBMoWuqgBqA8UG5kll32pA2MAEr4Evobs/s320/Pattern.png" alt="" id="BLOGGER_PHOTO_ID_5203286726774746850" border="0" /></a>The code we want to test is the <a href="http://xunitpatterns.com/SUT.html">system under test (SUT)</a>. It references a <a href="http://xunitpatterns.com/DOC.html">depended-on component (DOC)</a> library class.
<p/>
</div>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 <span><a href="http://xunitpatterns.com/Test%20Double.html">Test Double</a></span> to the SUT via <a href="http://xunitpatterns.com/Dependency%20Injection.html"><span>Dependency Injection</span></a> or <a href="http://xunitpatterns.com/Dependency%20Lookup.html"><span>Dependency Lookup</span></a> 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 [<a href="http://www.amazon.com/gp/product/0321545613?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321545613">Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321545613" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />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.
<h2>How it Works</h2>
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 <a href="http://xunitpatterns.com/Dependency%20Injection.html"><span>Dependency Injection</span></a> or <a href="http://xunitpatterns.com/Dependency%20Lookup.html"><span>Dependency Lookup</span></a>. In the production environment the thin wrapper is used. In the test environment we can replace the thin wrapper with a <span><a href="http://xunitpatterns.com/Test%20Double.html">Test Double</a></span>.
<h2>When to Use It</h2>
We have to use the <a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html">Own Library Interface</a> when we use a third party library class in our SUT which has both of the two following characteristics:
<ul><li>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.</li><li>The library class can not be replaced by a <span><a href="http://xunitpatterns.com/Test%20Double.html">Test Double</a></span>, because it does not inherit from an interface, it does not declare its methods as virtual or it has static methods.</li></ul>These circumstances very often lead to the smell <span><a href="http://xunitpatterns.com/Developers%20Not%20Writing%20Tests.html">Developers Not Writing Tests</a></span>. 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.
<h2>Implementation Notes</h2>
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 <a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html">Own Library Interface</a> 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 <a href="http://svengrand.blogspot.com/2008/03/recently-colleague-of-mine-which-is.html">TDD for Beginners</a> as an detailed example for the usage of the <a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html">Own Library Interface</a><a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html"></a> pattern.
We do not need to use the <a href="http://svengrand.blogspot.com/2008/05/new-xunit-test-pattern.html">Own Library Interface</a> pattern, when we can test our SUT together with the library class. For example the <span style="font-style: italic;">File</span> or <span style="font-style: italic;">Directory</span> 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.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0tag:blogger.com,1999:blog-1084762708281241901.post-51108102746164158702008-04-19T23:53:00.015+02:002009-01-04T22:27:36.227+01:00To become a better programmerI think some books might help to become a better programmer. This is my personal list:
<p/>
<span style="font-weight: bold;">Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides,</span> <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0201633612">Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0201633612" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
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.
<p/>
<span style="font-weight: bold;">Martin Fowler </span><a href="http://www.amazon.com/gp/product/0321127420?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321127420">Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321127420" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
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.
<p/>
<span style="font-weight: bold;">Martin Fowler, Kent Beck, John Brant, and William Opdyke </span><a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0201485672">Refactoring: Improving the Design of Existing Code (Addison-Wesley Object Technology Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0201485672" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
Beside the refactorings and the theory, this book helped me so much to convince my team members of the benefits of TDD.
<p/>
<span style="font-weight: bold;">Eric Evans </span><a href="http://www.amazon.com/gp/product/0321125215?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321125215">Domain-Driven Design: Tackling Complexity in the Heart of Software</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321125215" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
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.
<p/>
<span style="font-weight: bold;">Bertrand Meyer </span><a href="http://www.amazon.com/gp/product/0136291554?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0136291554">Object-Oriented Software Construction (Book/CD-ROM) (2nd Edition) (Prentice-Hall International Series in Computer Science)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0136291554" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
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.
<p/>
<span style="font-weight: bold;">Mary Poppendieck and Tom Poppendieck </span><a href="http://www.amazon.com/gp/product/0321150783?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321150783">Lean Software Development: An Agile Toolkit (Agile Software Development Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321150783" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
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.
<p/>
<span style="font-weight: bold;">Kent Beck </span><a href="http://www.amazon.com/gp/product/0321278658?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321278658">Extreme Programming Explained: Embrace Change (2nd Edition) (XP Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321278658" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
Although I never had the chance to work in a full blown XP project, this book is still a constant source of inspiration.
<p/>
<span style="font-weight: bold;">Kent Beck </span><a href="http://www.amazon.com/gp/product/0321146530?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321146530">Test Driven Development: By Example (Addison-Wesley Signature Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0321146530" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
If you start with TDD, read this book.
<p/>
<span style="font-weight: bold;">Gerard Meszaros </span> <a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&tag=whcodo-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0131495054">xUnit Test Patterns: Refactoring Test Code (Addison-Wesley Signature Series)</a><img src="http://www.assoc-amazon.com/e/ir?t=whcodo-20&l=as2&o=1&a=0131495054" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
<p/>
If you already worked a little bit with TDD, then read this book.
<p/>
I'm very sure everyone has its own list. I would be glad to here from other people about their favorite books.Svenhttp://www.blogger.com/profile/02929879501185148654noreply@blogger.com0