Groovy

The fuzz on conversational unit tests

I had the pleasure of being interviewed by Steven Devijver (of Grails fame) regarding easyb recently on the DZone– the title of the interview is dubbed “easyb: Introducing Conversational Unit Tests for Java.” I hadn’t thought about the term conversational when it comes to testing, but I think its right on, man! As the interview points out, with easyb, you can have conversational expectations that read quite nicely, such as

var.shouldNotBe null
and
var.length().shouldEqual 6 

If that code isn’t having a heart-to-heart with you regarding what var or its length should or should not be then I don’t know how to talk to you anymore, man.

Thanks, Steven, for the opportunity!

Metaprogramming is so Groovy

One of the hippest features of dynamic languages is the ability to modify fundamental aspects of the language at runtime — for example, Ruby’s open classes facilitate the addition of new methods at runtime– so for instance, you can easily add a blank? method to the String object. In Plain Jane Java you can’t actually add methods to Java’s String as it is a final class– what’s more, you can’t easily add methods to non-final classes at runtime either. With Groovy, however, you can.

Groovy has extensive metaprogramming facilities and one such addition is the ExpandoMetaClass, which enables you to do a host of copasetic things, including adding methods to normal Java objects (like String).

For example, imagine a domain object representing a runner in a race– a race can have 1 to many runners; consequently, a simple domain object for a runner could look like:

class Runner{
  def firstName
  def lastName
  def age
  def race
}

in which an instance of a Runner is connected to an instance of a Race (let’s keep this simple, man, so don’t worry about the fact that you think you can run in multiple races). Users go online and fill out a race application and invariably fail to capitalize the first character of proper names– hence, when race information is printed, some names appear inconsistent:

  • emily Smith
  • Gordon herch
  • bart simpson

Race organizers don’t care that people enter in names inconsistently, but they do want the official race ballets to reflect consistent-ness, man.

Ideally, the Runner domain object should have a fullName method, which returns “Emily Smith” instead of “emily Smith”– you could put some logic into the fullName method itself to manipulate the firstName and lastName properties; however, what if you need that same sort of first character capitalization technique else where?

You could look to a 3rd party library– such as Apache commons-lang, which actually does contain a capitalize method. This would certainly solve your dilemma, but you do have another option: just add a capitalize method to the String class itself, man.

To do so, you need to reference the metaClass property that all classes in Groovy expose– once you have it, you can dynamically add methods to that class itself by defining a closure. For instance, adding capitalize method is as easy as writing

String.metaClass.capitalize = {
 return delegate[0].toUpperCase() + delegate[1..<(delegate.length())]
}

As you can see, the delegate variable inside the closure is the instance of the outside object, which in my case is a String. Using some Groovy constructs, all I am doing is grabbing the first character of a String instance (via a positional construct) and calling toUpperCase to it, then I’m ensuring that the remaining characters (using an exclusive range) are returned– otherwise the capitalize method would return a single capitalized character.

I can verify things are copasetic via a handy assert:

assert "test".capitalize() == "Test"

I’m sure there are better, more efficient ways to code the capitalize method too (such as having the closure use commons-lang’s capitalize method!), suffice to say, man, this took all of 2 minutes.

Now, because it’s my bag, I can code my fullName method as follows:

def fullName(){
 return firstName.capitalize() + " " + lastName.capitalize()
}

The beauty of Groovy, of course, is that the above code is one of a few ways that method could be written– the return statement isn’t required and I could have used GStrings to convey the intent of the method in a nicer manner (i.e. "${firstName.capitalize()} ${lastName.capitalize()}").

Metaprogramming in Groovy is, as you can see, baby, hip and indubitably easy– what’s more, this capability brings unbridled power to Java applications– take a look under the covers of Grails (and Rails, for that matter, to see Ruby’s copasetic flexibility in action) and you’ll see what I mean. Dig it?

easyb SVN access is easier

The easyb code base has been moved to Google code, which has copasetic support for anonymous SVN access (which, unfortunately, didn’t work for QualityLabs). If you want to take a peek at what’s under the hood, simply type:

svn checkout http://easyb.googlecode.com/svn/trunk/ easyb-read-only

We’ve also created a hip easyb users group, so if you have any questions, comments, or rants, drop us a note!

DC’s so hip it’s Groovy

The Washington, DC area will be in the groove this coming February as super hip folks like Brian Sletten, Scott Davis, Neal Ford, Andres Almiray, Jeff Brown, Jason Rudolph, Graeme Rocher, Dierk Koenig, Alex Popescu, Scott Leberknight, and Venkat Subramaniam (to name just a few, man!) converge to chew the fat over Groovy, baby! These are some of the smartest people I know; consequently, if you have any interest in Groovy (or dynamic languages in general, man) you should plan on attending.

It promises to be a copasetic time, so if you’re planning on attending, let me know!

Stories are easy, man

Stories are a hip mechanism for clearly communicating intent– as Scott Ambler documented on his Agile Modeling site, stories are a

high-level definition of a requirement, containing just enough information so that the developers can produce a reasonable estimate of the effort to implement it.

What’s more, Dan North builds upon stories and defines them as

the scope of the feature along with its acceptance criteria

The beauty of stories, of course, is that copasetic customers (or domain experts, business analysts, etc) can write them– if they write them according to Dan North’s template, in which a story is essentially a series of scenarios, which read as:

  • given some context
  • when something happens
  • then something else should happen

then these scenarios (which make up a story) form a hip way to validate that what development is building actually meets a customer’s needs.

For instance, because it’s your bag, imagine a game of Blackjack, which, of course, is a simple game of cards adding up to 21. That is, each player is given two cards to start and subsequently can ask for more in an attempt to get to (or as close to) 21 without exceeding it. Essentially the player with the highest score (which isn’t greater than 21) wins the game, man.

In this case, imagine the customer is the casino (in which case, every scenario yields a bogue win for the dealer) or more specifically a blackjack dealer. The dealer could write a hip story with two simple scenarios as follows:

Story: blackjack
    scenario tie game when cards are dealt but dealer gets higher card
      given a game a blackjack game and both players have a score of 10
      when the dealer gets an ace and you get a 10
      then the dealer should win
    scenario tie game when cards are dealt but player gets higher card
      given a game a blackjack game and both players have a score of 10
      when the dealer gets a 10 and you get an Ace
      then the player should win

Using the latest and greatest hip incarnation of easyb, one can easily (did you really think I’d use a different adjective, man?) create a template that looks like this:

scenario "tie game when cards are dealt but dealer gets higher card", {
 given "a game a blackjack game and both players have a score of 10", {}
 when "the dealer gets an Ace and you get a 10", {}
 then "the dealer should win", {}
}

scenario "tie game when cards are dealt but player gets higher card", {
  given "a game a blackjack game and both players have a score of 10", {}
  when "the dealer gets a 10 and you get an Ace", {}
  then "the player should win", {}
}

As you can see, this copasetic code demonstrates two scenarios and would conceivably reside in a file named something like BlackjackStory.groovy– you’d of course need to fill in the business logic to verify the intended behavior. For example, the first scenario could be fulfilled as follows:

scenario "tie game when cards are dealt but dealer gets higher card", {

 given "a game a blackjack game and both players have a score of 10", {
  player = new Hand(Card.FIVE, Card.FIVE)
  dealer = new Hand(Card.TWO, Card.EIGHT)
  game = new Game(player, dealer)
 }

 when "the dealer gets an Ace and you get a 10", {
  dealer.hit(Card.ACE)
  player.hit(Card.TEN)
 }

 then "the dealer should win", {
  ensure(game.status()){
   isEqualToloss
  }
 }
}

You can then execute this story via Ant with easyb.

 <target name="behaviors" depends="unit-test">
  <taskdef name="easyb" classname="org.disco.easyb.ant.SpecificationRunnerTask">
   <classpath>
    <fileset dir="lib">
     <include name="**/*.jar"/>
    </fileset>
   </classpath>
  </taskdef>

 <easyb failureProperty="easyb.failed">
  <classpath>
    <path refid="build.classpath" />
    <pathelement path="target/classes" />
  </classpath>

  <report location="target/story.txt" format="txtstory" />
   <behaviors dir="behavior">
    <include name="**/*Story.groovy" />
   </behaviors>
 </easyb>

 <fail if="easyb.failed" message="easyb reported a failure"/>

</target>

The most hip part of this whole groovy thing is that after successfully invoking the behaviors target via Ant, you’ll get a story printed (in my case target/story.txt) that looks like this:

9 behavior steps executed successfully
  Story: blackjack
    scenario tie game when cards are dealt but dealer gets higher card
      given a game a blackjack game and both players have a score of 10
      when the dealer gets an Ace and you get a 10
      then the dealer should win
    scenario tie game when cards are dealt but player gets higher card
      given a game a blackjack game and both players have a score of 10
      when the dealer gets a 10 and you get an Ace
      then the player should win

In this Age of Aquarius, anyone (like customers, management, dance partners) can read that output and get a warm fuzzy feeling that their requirements are actually being coded! What’s more, if something breaks, the output will indicate a failure. Can you dig it?

Stories are hip. Stories are cool. Stories are easy with easyb, man!

The evolution of easy

Ensuring objects behave accordingly has been the primary goal of easyb; yet, initial attempts to utilize JBehave’s ensure framework seemed a bit too formal, man– the ensureThat chaining works naturally in Java (i.e. ensureThat(value, eq(false))); however, in Groovy it seems forced (i.e. ungroovy, baby).

Accordingly, easyb is in the process of introducing a new syntax for ensuring hip behavior via an ensure closure, that attempts to make object verification more natural. For example, taking the action of ensuring some value is false looks like:

ensure(value) {
 isFalse
}

or you could do:

ensure(value) {
 isEqualTo(false)
}

In fact, you can drop the ()’s too:

ensure(value) {
 isEqualTo false
}

As a side note, we want to provide a more simplified call, such as is false, however, is is defined magically in Groovy on all objects, so we’re working through this feature.

That’s a fairly simple example (how often is verification as easy as checking for false, man?).

Imagine you have a copasetic Person object (a plain old Java object, that is) that’s returned upon a find call or something and you’d like to ensure the Person object isn’t null and that a property, firstName, is some value (say “Kristen”).

Using the new easyb ensure syntax, it looks like this:

ensure(person){
 isNotNull
 and
 contains(firstName:"Kristen")
}

Note, the person object is a Java object– it looks like this:

public class Person {
 private String firstName;
 private int age;

 public Person(String firstName, int age){
  this.firstName = firstName;
  this.age = age;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 //...the rest omitted
}

If you wanted to ensure the age property was another value, you can add it to the map as follows:

ensure(person){
 contains([firstName:"Kristen", age:11])
}

The ensure clause can also evaluate expressions. If it’s your bag, and you don’t require a more rich verification, you can simply write stuff like:

ensure(value == 1)

Taking the first example (the top of this entry) where some value was supposed to be false, then becomes even easier:

ensure(!value)

Of course, the expression can be anything that resolves to a boolean.

ensure("this".equals("this") && "this" instanceof String)
and
ensure(!"this".equals("that"))

easyb is all about easy BDD, baby– the framework is evolving nicely and an updated release is imminent, which will formally include the new ensure syntax along with some more emphasis on stories and scenarios. Of course, if it’s your bag, baby, you can grab the source right now (apparently anonymous check-outs aren’t working so you’ll need to create a quick account on QualityLabs.org though)!

BDD in Java just got easier

Behavior driven development has been my bag lately; in particular, I have found the subtle shift in thinking in terms of behavior easier than that of tests. By thinking about behavior (which is, in essence, the specification of a hip object, for example), it becomes easier to validate things early-– in fact, when thinking in terms of a specification, it becomes copasetically easy to write things upfront. What’s more, one exceptional BDD framework, RSpec, has a remarkably hip DSL that reads like plain English, making the whole process easy (and fun).

Seeing how easy BDD is with RSpec inspired me to explore some similar options in Java– specifically, I teamed up with some hip friends and leveraged Groovy to create a flexible DSL for defining behaviors. The result is a framework dubbed easyb, baby.

easyb specifications are written in Groovy and are run via Java (currently, the command line or Ant); what’s more, easyb supports a few different styles of specifications ranging from RSpec’s copasetic it to a more story based DSL with disco givens, whens, and thens. The end result is a groovy framework that allows you to easily verify the behavior of normal Java objects, applications, packages, etc. Check out easyb today and see just how easy it is, man!

Many thanks to QualityLabs.org for hosting easyb– don’t forget to subscribe to the RSS feed to keep up with the project (and stay in the groove too)!

Groovy developers dig chicks

It’s no secret that hip disco dancers are a hit with the ladies; however, the big secret is that Groovy developers (or those that wish to be) are also fond of the ladies.

A few months back, I happened to check out GIA on Amazon and was amused to see some groovy data-mining in action.


(click the image to see a closer view, baby)

You had better believe that I haven’t ever hit print screen so quickly, man!

I’m not sure what’s more amusing– that fact that the iBatis book only has two stars or that the Grails book is better than the Pet of the Year?

Natural language verification

I find it particularly hip that, of late, it seems our industry is trying hard to bridge the gap that exists between stakeholders and developers– there are some undoubtedly copasetic tools like Fit to entire disciplines like BDD, which attempt to involve non-technical people in various ways.

For example, Fit enables stakeholders to specify trippin’ business rules (or the results of them) via tables, which are then logically implemented by hip developers. BDD stresses the notion of behavior and thus tries to get developers thinking like stakeholders in a more natural manner, man.

In particular, one disco BDD framework named RSpec comes very close to a simplistic DSL that arguably non-techincal users could take advantage of. Fairly recently, people have even created frameworks for executing simple text files (which is clearly the hippest thing ever, baby). Even Groovy has a similar BDD framework dubbed GSpec, which is modeled closely after RSpec.

One thing these copasetic frameworks have in common is a DSL that attempts to make the act of verification (either through tests like Fit or through specifications via RSpec, etc) easy. Accordingly, over the last few weeks, I’ve been playing around with a Groovy based framework (targeting Java developers) that attempts to mimic aspects of RSpec and JBehave’s story framework.

As I previously noted, the it closure delegates to JBehave, thus, everything you can do with JBehave’s hip ensure-like framework, you can do in this simple DSL– what’s more, I ended up adding three more closures that facilitate the notion of a story:

  • given some set up or copasetic context
  • when something happens
  • then ensure that something else should have happened, baby

You can use as many as you need too (i.e. a few givens and a few thens)– I haven’t figured out a good way to chain them, however, man. Moreover, as I began playing around with stories using this framework with existing projects, I noticed that stories are more user centric (no surprise); hence, the given aspect can be a bit heavy. Think about it for a second– normal unit tests rely on simple objects to verify; as these tests go up the stack, however, becoming component, integration, and system tests, the cost to set them up increases– databases have to be running, code needs to be deployed, filesystems, email servers, outside vendors all need to be accounted for (or mocked) in order to run higher level tests. The same is true for stories, if they are written from the standpoint of a smokin’ user.

Therein also lies the rub– end users, stakeholders, disco dancers, and other normal people not associated with the actual development of a system rarely understand its bowels– they shouldn’t either, by the way. This happens to be one area that hasn’t been elegantly solved– nevertheless, given that the set up of a story requires some plumbing in place (or the mocking thereof) I had to create a delegate for the given closure that facilitates putting a data-source into a known state.

One of my favorite frameworks for database seeding is none other than DbUnit– accordingly, using its hip API, I was able to create a simple delegate that requires database connection information (revision two will most likely take a live connection object too) and an associated XML document (in String form). The XML document is created in a closure, so you have a number of options. You can:

  • create an instance of a MarkupBuilder to create a data set
  • return a multiline String using the """ syntax
  • return the text of a seed file, like new File("./src/conf/seed.xml").text

Therefore, to create a groovy story, man, you can do this:

import org.springframework.context.support.ClassPathXmlApplicationContext

given "the database is properly seeded", {
 database_model("org.hsqldb.jdbcDriver",
  "jdbc:hsqldb:hsql://127.0.0.1", "sa", ""){
    """<?xml version='1.0' encoding='UTF-8'?>
   <dataset>
    <widget widget_id="1" type="drink" bnncd="hops"/>
    <line_item line_item_id ="20" widget_id="1" scne="789"/>
    <line_item line_item_id ="21" widget_id ="1" scne="33"/>
   </dataset>
   """
 }
}
//and
given "the DAO instance has been obtained from Spring", {
 context =
  new ClassPathXmlApplicationContext("spring-config.xml")
 dao = context.getBean("widgetDAO")
}

when "findWidget is called with a valid id", {
 wdgt = dao.findWidget("1")
}

then "a working Widget object should be returned", {
 ensureThat(wdgt, isNotNull())
 ensureThat(wdgt.getLineItems().size(), eq(2))
}

You can run these stories two different ways– either command line like so:

java org.disco.bdd.SpecificationRunner ./src/story/org/acme/MyStory.groovy

Or via Ant, like so:

<specificationrunner>
 <report location="${tareget}/report.xml"/>
 <behaviors>
  <fileset dir="${loc}/stories" include="**/*Story.groovy"/>
 <behaviors>
<specificationrunner>

The gap that exists between those that define requirements and those that write them hasn’t been bridged quite yet; however, we appear to be reaching that goal one hip iteration after another– in a perfect world, our customers would write the tests or at least tests could be generated by reading the requirements as written. I do believe that the story format demonstrated above does get us trippingly close– stakeholders could potentially write these or at least read them, no?

Using a little Groovy magic influenced by some spectacular frameworks, I think we are one step closer though. Dig it?

Incidentally, if it’s your bag and you want to play around with this simple behavior-story framework, you can download a snap shot of it. Please note that the distribution doesn’t have any documentation so you’ll have to read these posts until we write something up:

The distribution just includes a hip jar file (easyb-0.x.jar) and a few related runtime dependencies– if you don’t use the DbUnit given seeding stuff, then you can exclude the DbUnit and Crimson jars.

Joining the bash at CodeMash, man

As if seeing a groovy gal shave a dude’s head and hanging out with copasetic cats like my hip friends Neal Ford, Brian Sam-Bodden, and Chris Judd weren’t enough reasons to head out to Ohio for CodeMash, I’m pumped to have been invited to present two sessions and one open spaces event.

I’ll be speaking about BDD, Groovy, and a Martin Fowler inspired subject regarding the future of build languages. My BDD talk will obviously focus on how BDD can drive development more effectively than TDD and I’ll demonstrate some JBehave, RSpec, and a Groovy inspired RSpec knock-off. My Groovy session is a veritable crash course on using Groovy quickly– 101 style, baby. Lastly, the build languages openspaces session is an open discussion regarding Ant style (i.e. XML driven platforms like NAnt and MSBuild) build platforms versus more expressive platforms like Rake, Raven, and Gant, for example.

With sessions on Castle, Dojo, Grails, Rails, Scala, CI, and myriad other hip subjects, CodeMash looks like it is going to be a blast, baby– if you’re going to be there, let me know!

« Prev - Next »