Open minds leads to freedom

Communicating my thoughts on software development

Using Hamcrest and JUnit

Posted by rnaufal on 15th March 2010

Lately I started using the core Hamcrest matchers bundled with the JUnit framework to create more readable unit tests.

Hamcrest matchers were created to improve the readability of unit testing code. It’s a framework which facilitates the creation of matcher objects to match rules specified in unit tests. Some examples will let it to be clearer:

   1 import static org.hamcrest.CoreMatchers.equalTo;
   2 import static org.hamcrest.CoreMatchers.is;
   3 import static org.junit.Assert.assertThat;
   4 
   5 @Test
   6 public void shouldBeTheSamePerson()
   7 {
   8     Person me = new Person( "Rafael" );
   9     Person theOther = new Person( "Rafael" );
  10     assertThat( me, is( theOther ) );
  11 }
  12 
  13 @Test
  14 public void shouldHaveFixedSizeNumbers()
  15 {
  16     List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
  17     assertThat( numbers.size(), is( equalTo( 5 ) ) );
  18 }

The first example checks if one Person object is equal to another using the Object equals method, which was overridden in the Person class. The is syntax defines a matcher which is a shorthand to is(equalTo(value)). The second one uses the is(equalTo(value)) matcher to check the size of an integer list of fixed size numbers. The assertThat method is used in conjunction with the is(equalTo(value)) matcher, which makes the test sentence very human readable.

An interesting thing is the possibility to create a custom matcher, like this one which tests if a given list only has even numbers:

   1 public class AreEvenNumbers extends TypeSafeMatcher<Collection<Integer>> {
   2 
   3     @Override
   4     public boolean matchesSafely(Collection<Integer> numbers) {
   5         for (Integer number : numbers) {
   6             if (number % 2 != 0) {
   7                 return false;
   8             }
   9         }
  10         return true;
  11     }
  12 
  13     @Override
  14     public void describeTo(Description description) {
  15         description.appendText("even numbers");
  16     }
  17 
  18     @Factory
  19     public static <T> Matcher<Collection<Integer>> evenNumbers() {
  20         return new AreEvenNumbers();
  21     }
  22 }

And below are two tests which uses the AreEvenNumbers custom matcher:

   1 import static org.hamcrest.CoreMatchers.is;
   2 import static org.junit.Assert.assertThat;
   3 import static br.com.rafael.hamcrest.AreEvenNumbers.evenNumbers;
   4 
   5 @Test
   6 public void shouldHaveOnlyEvenNumbers()
   7 {
   8     List<Integer> numbers = Arrays.asList( 2, 4, 6, 8, 10 );
   9     assertThat( numbers, is( evenNumbers() ) );
  10 }
  11 
  12 @Test
  13 public void shouldNotHaveOddNumbers()
  14 {
  15     List<Integer> numbers = Arrays.asList( 1, 2, 4, 6, 8, 10 );
  16     assertThat( numbers, not( evenNumbers() ) );
  17 }

These two tests use the static factory method evenNumbers to instantiate the matcher on the test code. Not the use of the not matcher on the shouldNotHaveOddNumbers test to assert that no odd numbers are present on the given list. All tests use the static import feature, which turns the test not clean and not cluttered with the class qualification.

I haven’t experienced the other common matchers on unit testing code, like the Beans, Collections and Number ones. I think they turn the tests more readable, clean and easy to change. And you? Have you ever used Hamcrest matcher? If you have other examples of using it, post them here!

Updated: Static imports were added to the testing code.

Tags: , , , , , ,
Posted in Uncategorized | No Comments »

Joshua Block on How to Design a Good API & Why it Matters

Posted by rnaufal on 10th January 2009

In this talk (recorded at Javapolis), Joshua Block presents guidelines about how to design good APIs. I highlighted what i think are the most important parts of the talk:

  • Functionality should be easy to explain: If it’s hard to name, that’s generally a bad sign
  • Good names drive development
  • Be amenable to splitting and merging modules (If names are nasty, take a step back and make things easy to describe)
  • When in doubt, leave it out
  • You can always add, but tou cannot take it out
  • Implementation Should Not Impact API
  • Always omit implementation details
  • Inhibit freedom to change implementation
  • Don’t let implementation details “leak” into API (For example: Serializable, hash functions)
  • Minimize Accessibility of Everything (This maximizes information hiding)
  • Public classes should’nt have public fields
  • API should be easy to learn, read and use: It should be consistent, it’s a little language
  • Documentation matters (Example: Method contract between it and it’s clients)
  • Think of preconditions, postconditions, side-effects
  • Don’t Transliterate API’s
    • What’s the problem it solves?
    • What shoud abstractions did it use?
  • Don’t Make the Client Do Anything The Module Could do
  • Throw Exceptions to Indicate Exceptional Conditions

When you see the talk, post your comments here.

Tags: , , , ,
Posted in Uncategorized | 1 Comment »

Google announces Android

Posted by rnaufal on 6th November 2007

Google ended up the mystery and announced a mobile free development platform, called Android and not a GPhone, as someone would expect. This platform leverages the capacity of building rich mobile applications and service, promoting rich content for the consumer. It includes an operating system, user-interface and applications, letting developers build new mobile services equally, in a meaningful way. As Google says,

“We see Android as an important part of our strategy of furtheringGoogle’s goal of providing access to information to users wherever theyare. We recognize that many among the multitude of mobile usersaround the world do not and may never have an Android-based phone. Ourgoals must be independent of device or even platform. For this reason,Android will complement, but not replace, our longstanding mobilestrategy of developing useful and compelling mobile services anddriving adoption of these products through partnerships with handsetmanufacturers and mobile operators around the world.”

Dear readers, would it be the Web2.0 mobile revolution?

Tags: , , ,
Posted in Uncategorized | No Comments »

Google Guice, dependence Inversion in the Java way

Posted by rnaufal on 3rd June 2007

Check out this great video about the new Java based inversion control framework from Google. The guys Kevin Bourillion and Bob Lee explains the concept behind dependency inversion principle (dip) and the core features inside Google Guice, called ‘juice’. The framework embraces and uses annotations instead of string identifiers (heavily used in Spring) to inject dependencies into the code. The most interesting feature is that Guice injects constructors, fields and methods (any methods with any number of arguments, not just setters) . You can also integrate Spring with Guice. Enjoy!

Tags: , ,
Posted in Uncategorized | No Comments »

Google increasing its computing power

Posted by rnaufal on 20th June 2006

My friend Marcel Ferreira sent me this article which says Google is building two brand new data centers, as big as two football fields, on The Dalles, Ore. Google’s increasing power is reflected in the location of the data centers, near to a hidroeletric dam, in the Columbia river. Nice is “The cooling plants are essential because of the searing heat produced by so much computing power” :-).

Tags:
Posted in Uncategorized | No Comments »