Sunday, September 28, 2008

BDD in Java: practical example

Continuing last post about BDD, I would like to demonstrate an example with both xUnit and BDD tests. Because right now I'm developing mostly on Java, the JUnit and easyb are my choices for this small demo. So, let's start with our domain model.

Let's assume, we're modeling bank transfer subsystem. Needless to say, classes Bank and Account jibe well with our domain.

public class Account {
public void credit( final int amount ) throw NoEnoughMoneyException { ... }
public void debit( final int amount ) { ... }
public int getBalance() { ... }
}

public class Bank {
public void transfer( final Account from, final Account to, final int amount ) { ... }
}

These classes are so simple that I omitted all the code. Contracts only matter. The respective test case for money transfer looks like:

public class BankTestCase {
@Test( expected = NoEnoughMoneyException.class )
public void testTransfer() {
Bank bank = new Bank();
Account from = new Account( 100 ), to = new Account( 200 );
bank.transfer( from, to, 150 );
}
}

This test code is trying to provoke NoEnoughMoneyException by means of debit of the unallowed amount of money. Everything seems to be OK here. Now let's take a look how same test case looks in BDD:

scenario "Bank Transfer", {
given "an specific bank", {
bank = new Bank();
}

given "bank accounts", {
from = new Account( 100 );
to = new Account( 200 );
}

when "no enough money for transfer", {
transfer = {
bank.transfer( from, to, 150 )
}
}

then "exception should be thrown", {
ensureThrows( NoEnoughMoneyException ) {
transfer();
}
}
}


It's great, isn't it? You read it as a story.
And in fact output of this test scenario is real story:

Scenario Bank transfer
Given an specific bank
Given bank accounts
When no enough money for transfer
Then exception should be thrown

I like it. It's clear and friendly.

2 comments:

Andy said...

Well done! The easyb DSL supports substituting the second "given" with an "and" FYI. It might read more naturally that way:

Scenario Bank transfer
Given an specific bank
and bank accounts

Andriy Redko said...

Definitely agree. Thanks for pointing out to easyb DSL subtlety.