Use Hamcrest Matchers in JMockIt

JMockIt, when used together with Hamcrest matchers, can sometimes create very flexible verifications in unit test. This is demonstrated in the gist here.

The test class GameConrollerTest defines a test target (with @Tested) and a mocked object (in this case it is a class only with static methods, with @Mocked). In the only test method testCreatPerson(), it sets up an expectation, followed by invoking the target method under test, then finally provides a verification block to assert that some behaviors from the mocked object(class) have been invoked. The verification code snippet is provided below

    new Verifications() {
      {
        PersonFactory.createFighter(withArgThat(
            Matchers.allOf(Matchers.<Person>hasProperty("name", Matchers.equalTo(name1)),
                Matchers.hasProperty("age", Matchers.equalTo(age1)))));
        times = 1;
        PersonFactory.createFighter(withArgThat(
            Matchers.allOf(Matchers.<Person>hasProperty("name", Matchers.equalTo(name2)),
                Matchers.hasProperty("age", Matchers.equalTo(age2)))));
        times = 1;
      }
    };

The withArgThat() method can take any of the Hamcrest matcher of type <? super T> and returns an object of type T. This is where the magics happen because you can create a matcher that matches anything you need. In addition to the many convenient factory methods provided by Hamcrest Matchers util class, you can always provide your own matchers by implementing the Matcherinterface or extending any of its implementing classes. Here you can find a few good tutorials. Also you can refer to this one.

Advertisements
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s