Archive for BDD

Behaviour Matchers

JBehave and JMock2 are tools I’ve been using on my latest projects to define the behaviours of my objects. Both, when used together supplies pretty much all the resources needed to write effective behaviour verification. But in this topic I’m going to talk about JBehave Matchers.

Matchers are handy objects, inspired by JUnit Assert class, but much more elaborated. They can help us in loads of scenarios, without the need to write repeated code, such as loops, ifs, elses, turning out the code cleaner and much more intuitive. Currently there are six matcher subtypes: UsingArrayMatchers, UsingCollectionMatchers, UsingEqualityMatchers, UsingExceptions, UsingLogicalMatchers e UsingStringMatchers. For now, I’m just going to talk about four of them, which for me are the most innovative ones.

UsingArrayMatchers e UsingCollectionMatchers

Both are quite similar in their behaviours, the only thing that distinguishes them, as their names indicates, is the object on which operations are executed upon. I decided using the UsingArrayMatchers matcher to show some examples of features it comprises:

1 - Check if a Collection/Array contains a certain object:

2 - Check if a Collection/Array contains a certain set of objects:

3 - Check if a Collection/Array contains only a certain set of objects, and nothing more:

4 - Check if a Collection/Array contains a certain set of objects, in a defined order:

UsingStringMatchers

The methods in this class are self-explanatory, just check it out:

UsingLogicalMatchers

Using this class, it’s possible to negate any matcher and define matcher compositions using AND, OR, EITHER, BOTH. This class for me is the most powerful one, it gives us a wide range of interesting possibilities. Let’s try some of them, so you can see how far you can go.

1 - Using conditional matchers:

2 - Using negative matcher:

There are still a couple of matchers to talk about, one is the UsingEqualityMatchers class which is pretty much like JUnit Assert class, and the UsingExceptions class. Both also deserves your attention. Maybe someday I talk about them here. :)

Comments (3)