Apr 18 2011

iPhone Unit Test tips: Read a file in your test

Category: bdd,objective-cgiordano scalzo @ 12:44 pm

Very often I need to unit test something read from a file, but it seems very difficult to accomplish this simple task in iOS, so usually I give up.
But today I felt was a good day to find a solution ;-)
In my code I want to read a JSon data from a file, so I wrote a simple test:

describe(@"Conference", ^{
    it(@"loads given a filename", ^{
        Conference *conference = [[Conference alloc]initWithFile:@"talks_with_three_tracks"];
        [[theValue([conference hasData]) should] beTrue];
    });
});

with a simple init method:

-(id)initWithFile:(NSString *)filename{
    if ((self = [super init])) {
        NSString* path = [[NSBundle mainBundle] pathForResource:filename ofType:@"json"];
        NSError *error;
        NSString* talksString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        talks = [talksString JSONValue];
    }
    return self;
}

-(BOOL)hasData{
    return talks!=nil;
}

Unfortunately it doesn’t work :-( , because path is nil;
But here it isthe solution:
instead of using [NSBundle mainBundle], we should use the bundle associated with our class:

        NSString *path = [[NSBundle bundleForClass:[Conference class]] pathForResource:filename ofType:@"json"];

Simple and neat: thank you StackOverflow ;-)

Technorati Tags: , ,

Tags: , ,


Mar 17 2010

AgileCamp 2010: richness of difference

Category: agile,bdd,me,objective-c,presentationgiordano scalzo @ 2:59 pm

Some weeks ago, I has been lucky enough to attend to AgileCamp 2010, an awesome Barcamp organized by Sketchin, a Swiss UX and Web agency.
With my good fellows XpUg-gers Gabriele, Andrea and Indrit, we reached a lot of old and new friends, all of them caring about quality and “Things Got Right”.
I came back really enriched, mainly because I met people with experiences and point of view different than mine.

It has been my first Barcamp, so I though it was necessary to present something, and I decided to assemble a little introduction to Tdd coding for Iphone.

Here there is the video of my presentation:

AgileCamp – iPhone agile DEV (di Giordano Scalzo) from Sketchin on Vimeo.

Technorati Tags: , ,

Tags: , ,


Dec 17 2009

StringCalculator Kata at Xpug

Category: agile,bddgiordano scalzo @ 2:18 pm

Last evening the wonderful Xpug Milano hosted a Kata Meeting: three people, three language, one problem, one pomodoro each!

After the launch of http://katacasts.com/, this kind of practice has begun to spread around the world.

As far as I know, that was one of the firsts meeting held in Italy and it has been exciting (and a little scaring) to be one of the performer.

The simple problem to solve was the StringCalculator kata, proposed by Roy Osherove as simple exercise to repeat to assimilate Tdd.

Luca Marrocco performed the kata in Ruby, Raffaele Salmaso a Python version, the benevolent dictator of Xpug Milano a backup kata in Erlang, and yours truly a Scala version.

Below the live recording of my session, with errors, mistakes and pauses made during the execution:

StringCalculator in Scala Kata live at Xpug Milano from giordano scalzo on Vimeo.

Any kind of suggestion about the solution, the process, the way I performed are absolutely welcome.

Technorati Tags: , ,

Tags: , ,


Dec 04 2009

An evening at Xpug: Bdd presentation

Category: agile,bdd,me,presentationgiordano scalzo @ 10:24 pm

Last evening, I gave a speech about Bdd, at the wonderful Milan XPUg.
The meeting has been very pleasant: I believe the members are among the most brilliant mind I know.

I could admit I didn’t know very well Bdd, but following the good old advice “teach to learn“, I got a triple win:
I taught something new to Xpug guys, I learned a lot of new things and I improved my presentation skill.

Moreover, after a couple of hours after I put online my slides, the Slideshare team promoted my presentation in home page as features presentation: what a great result for a weekend presentation hack!

Technorati Tags: , ,

Tags: , ,


Oct 15 2009

Gibbon: add story to RSpec

Category: bdd,rubygiordano scalzo @ 10:31 am

I really do like Rspec and so do Cucumber, but, often, I don’t like switch between them during my develompment.
Today I stumbled upon ‘Gibbon‘ a clever hack by Stephen Caudill, of tomatoi.st fame,
that add support for GIVEN/WHEN/THEN templates.

It simple needs to add this file into your spec/support directory:

module Spec::DSL::Main
  alias :Feature :describe
  def Story(description)
    @description_args.push("\n#{description}\n")
  end
end

module Spec::Example::ExampleGroupMethods
  def executes(scope=:all, &blk)
    before(scope, &blk)
  end

  def Scenario(description, &blk)
    describe("Scenario:  #{description}", &blk)
  end

  def Background(description, &blk)
    describe("Background #{description}", &blk)
  end

  def Given(description, &blk)
    describe("Given #{description}", &blk)
  end

  def When(description, &blk)
    describe("When #{description}", &blk)
  end

  def Then(description, &blk)
    example("Then #{description}", &blk)
  end

  def And(description, &blk)
    example("And #{description}", &blk)
  end

  def But(description, &blk)
    example("But #{description}", &blk)
  end
end

and it’ll be possible write specs like that:

  Feature "A Tomatoist does a pomodoro" do
    Story <<-eos
    In order to perform a focused unit of work
    As a Tomatoist
    I want to start a pomodoro
    eos

    Scenario "Starting a pomodoro" do
      When "I go to the home page" do
        executes { visit '/' }

        Then "I should be sent to a new session" do
          current_url.should =~ /\/\w{3,}/
        end

        And "I should see an unstarted timer" do
          response.should have_tag('#timer .countdown_row','00:00')
        end

        And "I should see a pomdoro button" do
          response.should have_tag('input[type=submit][value=?]','Pomdoro')
        end

        When "I click the pomodoro button" do
          executes do
            @session_url = current_url
            click_button 'Pomodoro'
          end

          Then "I should be on my session's page" do
            current_url.should == @session_url
          end

          And "my timers should have been initialized" do
            response.should have_tag('#timer .countdown_row','25:00')
          end

          And "my timer history should show the current pomdoro" do
            response.should have_tag('#history ul li', /Pomodoro/, 1)
          end

          And "the pomodoro button should be highlighted" do
            response.should have_tag('form.current input[type=submit][value=?]','Pomdoro')
          end
        end
      end
    end
  end
  

Neat hack, indeed!

I'll try it as soon as possible.

Technorati Tags: ,

Tags: ,


Sep 22 2009

Bowling Kata with Ruby and RSpec

Category: bdd,ruby,Uncategorizedgiordano scalzo @ 8:59 pm

Looking around in daily feeds reading, suddenly I realized I never practiced the first code kata: that Bowling Kata that started all.
I decided to implement it while exploring RSpec and configuring my Ruby environment for Windows:
I used to do my programming under friendly Ubuntu, but because my recent jobs duties in Delphi, mainly I use a Windows Xp system.

Installing Ruby is straightforward thanks to RubyInstaller, a wonderful project that let you configure a Ruby environment under Windows; to dive into a complete Bdd flow I configured autospec and Growl following this useful post: I advice every Bdd practitioner to give autospec a try, it can save a lot of windows and mental switch… but it can’t be told, try it and enjoy it.

While I’m very happy with Eclipse during Java coding, I never found a satisfactory editor for Ruby code.
So I decided to try to enter in guru world and use Vim, adding a bunch of useful plugin, as the wondeful snipMate that import the Textmate snippets under Vim.

Back to kata, these are my specs:

require File.join(File.dirname(__FILE__), "//spec_helper")

describe Bowling do

	before(:each) do
		@game = Bowling.new
	end

	def roll_many(num, pins)
		num.times do |hit|
			@game.hit(pins)
		end
	end

	it "should score 0 for gutter game" do
		roll_many(20, 0)
		@game.score.should == 0
	end

	it "should score 20 for a pin each frame" do
		roll_many(20, 1)
		@game.score.should == 20
	end

	def roll_spare()
		@game.hit(5)
		@game.hit(5)
	end

	it "should score 20 when make a spare and 3 and 4 after " do
		roll_spare
		@game.hit(3)
		@game.hit(4)
		roll_many(16, 0)
		@game.score.should == 20
	end

	def roll_strike()
		@game.hit(10)
	end

	it "should score 24 when make a strike and 3 and 4 after " do
		roll_strike
		@game.hit(3)
		@game.hit(4)
		roll_many(16, 0)
		@game.score.should == 24
	end
end

They are virtually identical to UncleBob’s ones.

And this is my code:

class Bowling
	private
	class Frame
		def initialize
			@rolls = []
			@rolls[0] = @rolls[1] = 0
			@index = 0
		end

		def sum
			@rolls[0]+@rolls[1]
		end

		def strike?
			@rolls[0] == 10
		end

		def spare?
			sum == 10 && !strike?
		end

		def bonus_for_strike
			sum
		end

		def bonus_for_spare
			@rolls[0]
		end

		def pins=(value)
			@rolls[@index] = value
			@index = @index + 1
		end

		def finished?
			@index > 1 || strike?
		end

	end

	def add_frame?
		@frames.empty? || @frames.last.finished?
	end

	public

	def initialize
		@frames = []
	end

	def hit(pins)
		@frames << Frame.new if add_frame?
		@frames.last.pins=pins
	end

	def score
		was_spare = false
		was_strike = false
		@frames.inject(0) do |score, current_frame|
			if(was_strike)
				score = score + current_frame.bonus_for_strike
			end
			if(was_spare)
				score = score + current_frame.bonus_for_spare
			end
			was_spare = current_frame.spare?
			was_strike = current_frame.strike?

			score + current_frame.sum

		end
	end
end

I'm quite satisfied for the result, I like the encapsulation of responsibility inside Frame, but I don't like at all the fact I saved a state during the score's calculation: I will focus on that in next practice.

At last, the environment created has been very friendly, I didn't miss Eclipse for normal developing, maybe I miss a bit a helper for extracting method, but with snippets and the Vim shortcuts, I gained a lot of productivity.

Technorati Tags: , , , , ,

Tags: , , , , ,


Sep 17 2009

Using JDave: A quick introduction to specs framework

Category: bdd,java,tutorialgiordano scalzo @ 5:13 pm

As second Bdd engine to try, I choose JDave, a specification oriented engine.
JBehave is, instead, user-stories-oriented: the difference is very subtle and I’m not sure I caught it completely ;-) .
Anyway, JDaveis inspired by RSpec, at the moment the most used bdd engine, so I thought it deserved a try.
In order to compare JDave with JBehave, I implemented the StringTemplater kata, as in my previous post.

Installing JDave

After creating a java project, I simply downloaded the last version of JDave and extracted all jar in lib directory of my project:

JDave Jars

They are a lot of jars, and I’m sure I won’t use all of them, but it’s just a try so it doesn’t deserve the time to filter only the used ones.

JBehave is a story runner, so each scenario must be written as:

Given something
When something happens
Then this happens

Instead, JDave is a specification engine and each scenario show a behavior of a class:

AThingIWantToWrite
  - ShouldDoThis
  - ShouldDoThat
  - ShouldntDoThat

In other words, JBehave is similar to Cucumber, JDave is similar to RSpec.

Writing a specification is really straightforward:
first of all, we create a Specification object, passing the object we want to write; then we create a serie of inner classes:

@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification<ThingIWantToWrite> {
	public class AThingIWantToWrite {
		public void ShouldDoThis() {
		}
		public void ShouldDoThat() {
		}
        }
   ...
}

As JBehave, JDave is a wrapper built over JUnit, so we can use our Ide integration to run the specifications.
That’s it!

The code

As in JBehave try, I implemented the same scenarios as in Corey Haines Video:

package biz.scalzo.kata.stringtemplater.jdave;

import org.junit.runner.RunWith;

import jdave.Specification;
import jdave.junit4.JDaveRunner;

@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification<StringTemplater> {
	public class AStringTemplater {
		private StringTemplater stringTemplater;

		public void create() {
			stringTemplater = new StringTemplater();
		}

		public void shouldReturnEmptyWhenAnEmptyStringIsPassed() {
			specify(stringTemplater.replace(""), must.equal(""));
		}

		public void shouldReturnTheOriginalStringWhenNoMarkersArePassed() {
			specify(stringTemplater.replace("original string"), must.equal("original string"));
		}

		public void shouldReplaceAToken() {
			specify(stringTemplater.replace("Hello, $name","name: giordano"),
					must.equal("Hello, giordano"));
		}

		public void shouldReplaceTwoTokens() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano, attitude:  wonderful"),
					must.equal("Hello, giordano, how a wonderful day"));
		}

		public void shouldRemoveNotProvidedMarkers() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano"),
					must.equal("Hello, giordano, how a  day"));
		}
	}

}

The Junit view of Eclipse is very explicative of the behaviors of StringTemplater:
JUnit View

For sake of completeness, this is the final implementation of StringTemplater:

package biz.scalzo.kata.stringtemplater.jdave;

import java.util.Arrays;
import java.util.Iterator;

public class StringTemplater {

	public String replace(String stringToReplace) {
		return replace(stringToReplace, "");
	}

	public String replace(String stringToReplace, String markers) {
		return replace(stringToReplace, initialIterator(markers));
	}

	private String[] tupla(String pair) {
		return pair.split(":");
	}

	private Iterator<String> initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

	private String replace(String stringToReplace, Iterator<String> markers) {
		if (!markers.hasNext())
			return stringToReplace;
		String[] pair = tupla(markers.next());
		String newString = stringToReplace.replace(name(pair), value(pair));
		return replaceEmptyMarkers(replace(newString, markers));
	}

	private String replaceEmptyMarkers(String replace) {
		return replace.replaceAll("\\$\\w+", "");
	}

	private String value(String[] pair) {
		return (pair.length != 2) ? "" : pair[1].trim();
	}

	private String name(String[] pair) {
		if (pair.length != 2)
			return "";
		return "$" + pair[0].trim();
	}
}

Conclusions

JDave is very easy to learn and the specifications written throught it are very complete and expressive.
If I have to make a choice, I liked slightly more JDave, but I think are just two tools: BDD is a way to think, not a framework or an engine to use.

In conclusions, I believe JBehave and JDave could be used together, the former to describe the user stories, at user level, the latter to describe the behaviors of the classes, at developer level.

Technorati Tags: , , ,

Tags: , , ,


Sep 09 2009

Infinitest: an autotest for Eclipse

Category: agile,bdd,javagiordano scalzo @ 7:00 pm

In my experimental trips in Ruby world, other than the elegance of the language, the Bdd as default and the lot of new exciting things created by the community, a thing I liked a lot was autotest , a little gem that launches our testsuite when we change a source file.
It could seem a silly utility, but I can assure it’s a really time saver and can take us in a high productive mental flow: I really missed it in Java world.

Of course, I’ve heard about Junit Max, the Kent Beck’s attempt to create a product, but my laziness delayed me to try it, until Kent got bored and dismiss the project :-( .

Today while reading distractedly the Twitterverse, I bumped into Infinitest, that seems exactly what I was looking for.
Infinitest isn’t open source, but for personal use it should be possible get a free of charge individual license.

The installation is straightforward as usual, just add http://update.improvingworks.com to Eclipse’s software updates, and we are ready to start!

Infinitest stay in the right bottom of Eclipse, waiting far some changes:

waiting for changes

When we save some file Infinitest starts and show the results of all test it founds in the project:

red test

A nice feature is the yellow bar when there is some error in the workspace and tests can’t run:

yellow bar

That’s all!
I have to try it more, but it seems very promising and useful.

Technorati Tags: , , , ,

Tags: , , , ,


Sep 04 2009

Bdd with JBehave

Category: bdd,java,tutorialgiordano scalzo @ 1:50 pm

Somebody defined Behaviour-Driven Development “TDD done right”; maybe is a bit too provocative as definition, but I think it’s the time to get my hands wet and give Bdd a chance.

JBehave is the first BDD’s framework, developed by the BDD’s inventor himself, Dan North, and still one of the more supported in Java community.

I choose a simple kata to develop in Bdd-way, the StringTemplater kata, as saw in a Corey Hainesvideo and following this excellent post.

JBehave on Eclipse: half an hour tutorial

First of all, we should create a project under Eclipse and add JBehave jars.

Then we should write the basic infrastructure: a textual file with the scenarios and two classes connecting our stories to JBehave.

By default the scenarios file should be without extension and in the same directory of classes, but, aiming to separate specs code and production code, I created a new source directory called scenario.

The scenarios file should have a meaningful name and the words should separated by underscores; in this example I called it replace_tokens_in_string.

At the beginning of the file, we can write the story we should implement: it isn’t mandatory, but it’s useful if we use specs to comunicate with the customers.
Following we can write a first basic scenario:

Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring

The story is just descriptive, but the scenario must be of the form of
Given something
When action
Then check

Now we need create two java classes.
The first one is JBehave wrapper to JUnit TestCase and its name should match the one of textual file converted in CamelCase: in our example should be ReplaceTokensInString.

package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.Scenario;

public class ReplaceTokensInString extends Scenario{
	  public ReplaceTokensInString() {
	        super(new ReplaceTokensInStringSteps());
	    }
}

The second class, ReplaceTokensInStringSteps, implementing the steps of the scenario:

package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
}

That’s it!
As said before, JBehave is built over JUnit so we can run ReplaceTokensInString as Junit test obtaining a message from the engine:

Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string

Given I have a StringTemplater (PENDING)
When I ask to replace an emptystring (PENDING)
Then I should get an emptystring (PENDING)

PENDING means we have to build that step; so we do it with an empty implementation:

package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	@Given("I have a StringTemplater")
	public void createStringTemplater() {
	}
	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
	}
	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
	}
}

and when we run again the test, the PENDING messages should disappear.

This is the basic infrastructure, but, in my tiny experience was the most difficult part: once the empty scenario worked, implement the complete kata was quite straightforward.

This is my final scenarios file:

Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring

Scenario: replace string without tokens
Given I have a StringTemplater
When I ask to replace 'this string'
Then I should get 'this string'

Scenario: replace string with a token
Given I have a StringTemplater
When I ask to replace 'Hello, $name' with [name : pippo]
Then I should get 'Hello, pippo'

Scenario: replace string with two tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo, attitude: wonderful]
Then I should get 'Hello, pippo, how a wonderful day'

Scenario: replace string with two adjacent tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $adj$name' with [name : friend, adj: good]
Then I should get 'Hello, goodfriend'

Scenario: replace string with two tokens and only one value
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo]
Then I should get 'Hello, pippo, how a  day'

This my steps:

package biz.scalzo.kata.stringtemplater.jbehave;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.jbehave.Ensure.ensureThat;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	private StringTemplater templater;
	private String result;

	@Given("I have a StringTemplater")
	public void createStringTemplater() {
		templater = new StringTemplater();
	}

	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
		result = templater.replace("");
	}

	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
		ensureThat(result, is(equalTo("")));
	}

	@When("I ask to replace '$stringToReplace'")
	public void replaceStringWithoutTokens(String stringToReplace) {
		result = templater.replace(stringToReplace);
	}

	@Then("I should get '$expected'")
	public void checkStringResult(String expected) {
		ensureThat(result, is(equalTo(expected)));
	}

	@When("I ask to replace '$stringToReplace' with [$tokens]")
	public void replaceStringWithTokens(String stringToReplace, String tokens) {
		result = templater. replace(stringToReplace,tokens);
	}

}

and, last but not least, StringTemplater class:

package biz.scalzo.kata.stringtemplater.jbehave;

import java.util.HashMap;
import java.util.Map.Entry;

public class StringTemplater {

	public String replace(String originaleString) {
		return replace(originaleString, "");
	}

	public String replace(String stringToReplace, String tokensAsString) {
		HashMap tokensMap = splitTokens(tokensAsString);
		return removeKeywordWithoutValue(replaceKeywords(stringToReplace,
				tokensMap));
	}

	private String removeKeywordWithoutValue(String replaceKeywords) {
		return replaceKeywords.replaceAll("\\$\\w+", "");
	}

	private String replaceKeywords(String initialValue,
			HashMap tokensMap) {
		String result = initialValue;
		for (Entry entry : tokensMap.entrySet()) {
			result = result
					.replaceAll("\\$" + entry.getKey(), entry.getValue());
		}
		return result;
	}

	private HashMap splitTokens(String tokensAsString) {
		String[] pairs = splitPairs(tokensAsString);

		HashMap result = new HashMap();
		for (String pair : pairs) {
			String[] tokens = pair.split(":");
			if (tokens.length > 1) {
				result.put(tokens[0].trim(), tokens[1].trim());
			}
		}
		return result;
	}

	private String[] splitPairs(String tokensAsString) {
		return tokensAsString.split(",");
	}
}

Conclusions

This is my first impact with Bdd in Java, I liked and I think it’s very promising.
Neverthless, I still don’t know if it is something I can do in day by day work or just a proof of concept: Jbehave is quite verbose and the stories are high level specifications, so we need to write a lot of boilerplate code to specify a class.

In my trip in Bdd-land, next steps will be give other Bdd engines a try, starting with ones written in high level languages as easyb or scalatest.

Technorati Tags: , , , , ,

Tags: , , , , ,