Introduction to Hamcrest String Matchers
Another week, another blogpost. For those catching on just now, or finding this post using a search engine; I’m writing a series of posts about Hamcrest, a framework for writing test matcher objects, and showing you how to use Hamcrest. While the previous post was about the Core Matchers, the topic of this week is Hamcrest String Matchers.
The Hamcrest String Matchers are the following:
containsString, startsWith, endsWith, equalToIgnoringCase, equalToIgnoringWhitespace, isEmpty, isEmptyOrNull and stringContainsInOrder
Also in this post, I will give an example of all of them in the code block below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
@Test public void testMovieStringMatchers() { // Setting up our class to test here. Movie movie = new Movie("Charlies Angels"); movie.setDescription(""); movie.setDirector(null); movie.setStoryLine("The captivating crime-fighting trio who are the masters of disguise, espionage and martial arts."); // Checks that the actual result contains the specified String assertThat(movie.getTitle(), containsString("Angels")); // Checks that the actual result starts with the specified String assertThat(movie.getTitle(), startsWith("Charlies")); // Checks that the actual result ends with the specified String assertThat(movie.getTitle(), endsWith("Angels")); // Checks that the actual result equals the specified String, ignoring casing assertThat(movie.getTitle(), equalToIgnoringCase("charlies angels")); // Beware: this method work different than you would expect, since it doesn't ignore whitespaces: it ignores most of them. Check the Javadoc. assertThat(movie.getTitle(), equalToIgnoringWhiteSpace(" charlies angels ")); // Checks that the actual result is an empty String assertThat(movie.getDescription(), isEmptyString()); // Checks that the actual result is null or an empty String assertThat(movie.getDirector(), isEmptyOrNullString()); // Checks that the actual result contains the specified Strings in this sequence assertThat(movie.getStoryLine(), stringContainsInOrder(Arrays.asList("The", "trio", "arts"))); } |
Again, the Hamcrest assertions are very clear, and makes your testcode a easier to read an maintain. Enjoy!