Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Tomek Kaczanowski - Practical Unit Testing with JUnit and Mockito - 2013.pdf
Скачиваний:
228
Добавлен:
07.03.2016
Размер:
6.59 Mб
Скачать

Chapter 6. Things You Should Know

6.5. Stubbing Void Methods

Sometimes it is required to stub void methods. Mockito allows to do it, but there is a small catch: the syntax differs substantially from what we have learned so far. For example, to stub the behaviour of someMethod() method you would usually write the following:

Listing 6.11. Stubbing a non-void method

when(someObject.someMethod()).thenReturn("some value");

However, if a method returns void, then the syntax differs (obviously it does not make sens to return anything from void method, so in the example below we instruct the voidMethod() to throw an exception):

Listing 6.12. Stubbing a void method

doThrow(new IllegalArgumentException("bad argument!"))

.when(someObject).voidMethod();

As the original Mockito’s documentation states, this different syntax is required, because: "Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets…".

Apart from the doThrow() method, there are two other methods which may help when working with void methods: doNothing() and doAnswer(). Mockito documentation discusses them in detail, giving very good examples for both.

6.6. Matchers

Up to now we have been almost exclusively using standard JUnit assertions. We have used assertTrue() to verify some basic boolean expressions, assertEquals() to compare two objects with respect to equality, and assertNull() or assertNotNull() to make sure that a given object is or is not null, etc. These basic assertions are enough to verify any condition you might think of. That is true, but there is still room for further improvement here! In particular, thanks to using matchers we can have more readable test code, which is always a good thing.

6.6.1. JUnit Support for Matcher Libraries

Let us dive into history for a minute. A long time ago, Hamcrest was the only matchers library available in the world of Java. At this time a decision was made to facilitate its use for JUnit users and an additional assertion method - assertThat() - was added to the Assert class right next to our old friends assertEquals, assertTrue and others. This addition to the JUnit API seemed right at the time, but after a few years, when new matchers libraries had emerged, it had become a legacy mistake. This is not to say that there is anything wrong with Hamcrest! Not at all: it is still a very good, successful and very popular tool. However, the presence of the Hamcrest-related assertThat() method in the JUnit API makes developers think that it is the matchers library to be used with JUnit.

Currently, there are two matchers libraries for Java developers that are the most popular ones: Hamcrest and FEST Fluent Assertions. They are very similar in terms of the functionalities offered, but differ

110

Chapter 6. Things You Should Know

when it comes to the API. The main difference is that FEST offers a fluent interface API. This works very well with the auto-completion feature of current IDEs, and this is one of the reasons why I value it above Hamcrest.

The reality is that you can use any matcher library with JUnit tests with ease. Usually, all you need to do is import an adequate class (an equivalent to the Assert class of JUnit); that really is all! For example, to use the FEST Fluent Assertions matchers library all you need to do is import the

org.fest.assertions.Assertions class.

The information included in this section is valid across all currently existing implementations of matchers; you can use what you learn here with both FEST and Hamcrest (the two most popular frameworks of this kind). All the examples will be written with FEST, but only because this is my tool of choice.

6.6.2. Comparing Matcher with "Standard" Assertions

In some sections of this book we have already mentioned that there are two aspects to the readability of assertions: how they look within the test code, and what information is given to the developer once an assertion has failed. Matchers are particularly useful for helping with both of these issues.

Matchers makes your tests more readable. They provide extra readability at a linguistic level, because the order of words in assertThat(worker).isA(manager) resembles natural language much more closely than does assertEquals(worker, manager), the standard assertEqual() assertion. This is true both for FEST or Hamcrest matchers available out-of-the box, and for custom matchers that you yourself write. The following example demonstrates this:

Table 6.1. Comparison of default JUnit assertions and FEST matchers

standard JUnit assertions

 

 

 

 

Book book = new Book(TITLE);

 

 

 

assertNotNull(book.getTitle());

 

 

 

assertFalse(book.getTitle().isEmpty());

 

 

 

assertEquals(TITLE, book.getTitle());

 

 

 

 

 

FEST matchers

 

 

 

Book book = new Book(TITLE);

 

 

 

assertThat(book.getTitle()).isNotNull();

 

 

 

assertThat(book.getTitle()).isNotEmpty();

 

 

 

assertThat(book.getTitle()).isEqualTo(TITLE);

 

 

 

 

 

You may also notice that the use of matchers introduces a specific "rhythm" to your assertions: they all read similarly.

6.6.3. Custom Matchers

But so far this is nothing to get especially excited about. We can do more than this by writing custom matchers, which are designed to verify properties of our domain object. For example, would it not be nice to replace the assertion on a book’s title property with a simple assertThat(book).hasTitle(TITLE)? Absolutely! This is possible, even though creating such a matcher comes at a certain cost. Listing 6.13 shows the code of a custom matcher that will furnish us with the aforementioned hasTitle() method:

111

Chapter 6. Things You Should Know

Listing 6.13. Implementation of a FEST custom matcher

import org.fest.assertions.*;

public class BookAssert extends GenericAssert<BookAssert, Book> {

public BookAssert(Book actual) { super(BookAssert.class, actual);

}

public static BookAssert assertThat(Book actual) { return new BookAssert(actual);

}

public BookAssert hasTitle(String title) { isNotNull();

String errorMessage = String.format(

"Expected book's title to be <%s> but was <%s>", title, actual.getTitle());

Assertions.assertThat(actual.getTitle())

.overridingErrorMessage(errorMessage)

.isEqualTo(title); return this;

}

}

Import of required FEST classes.

Our implementation of assertThat() is required, so that we can start assertion lines in the same way as we would start any matchers’ assertions. Then we can chain together both the default matchers

(e.g. isEqualTo(), isNotNull()) and our custom hasTitle() matcher.

Here we have a custom matcher responsible for verifying equality as regards book title, with respect to any given book. It also contains a null check (isNotNull()), so that the test code will be safe

from any NullPointerException error.

The error message is overridden here, so that if the assertion fails the developer will know exactly what happened (e.g. "Expected book’s title to be <Hobbit> but was <Odyssey>"). This is yet another advantage of matchers, which can provide very readable failure messages in cases of failed assertions.

Now that we have this custom matcher implemented, we can use it in our test code as shown below:

Listing 6.14. The use of a custom matcher

import org.junit.Test;

import static com.practicalunittesting

.chp06.matchers.BookAssert.assertThat;

public class BookFestTest {

private static final String TITLE = "My book";

@Test

public void constructorShouldSetTitle() { Book book = new Book(TITLE);

assertThat(book).hasTitle(TITLE);

}

}

In this case we use the assertThat() method provided by the BookAssert class.

112

Chapter 6. Things You Should Know

As shown in the listing above, custom matchers also help to achieve better readability by helping us to write the tests at a reasonable level of abstraction. This is possible because custom matchers can contain some assertions within themselves and so act as superordinate assertions under intentionrevealing names. The association with private methods, which are often used in test code to achieve exactly the same goal, is justified. However the syntax of matchers makes them even more readable.

Another interesting point about matchers is that they are highly reusable. They can be used in connection with a great many test methods and test classes. Moreover, they can be combined together to create complex assertions, as shown in Listing 6.15. This example also demonstrates that it is possible to combine default matchers (isNotIn()) with custom ones (hasTitle() and isWrittenIn()).

Listing 6.15. Combining matchers

public void combinedMatchersExample() { Book book = new Book(TITLE);

assertThat(book).hasTitle(TITLE)

.isNotIn(scienceFictionBooks)

.isWrittenIn(ENGLISH);

}

Such simple examples hardly reveal the true power and usefulness of matchers. Custom matchers excel particularly when working with rich domain objects or complex data structures.

6.6.4. Advantages of Matchers

It is time to list the advantages of matchers, which are numerous:

they enhance code readability,

they help us to write assertions on the right abstraction level,

they help to remove logic from tests (and encapsulate it within the matchers’ classes),

they are highly reusable, which is very important if your domain objects are complex and are tested with multiple test scenarios,

many matchers are available directly from matcher libraries - including specific matchers for work with collections (as shown in Section 6.12) or exceptions (see Section 6.4),

writing custom matchers is a relatively simple task.

In spite of their usefulness, I do not see matchers being used much. I guess the main reasons for this are lack of knowledge about them, a general reluctance to add yet another library to one’s project, and the cost involved in implementing custom assertions. Personally, I find them invaluable, especially when working with rich domain objects. As soon as I no longer feel comfortable using the default assertions (assertEquals(), assertTrue()), I write a custom matcher instead. Usually this solves my problem.

In my experience, it quite often happens that the custom matchers one has written for unit tests get reused later for integration and/or end-to-end tests. This increases the "return on the investment" one had to make to implement them.

As a last tip, I would suggest that if you use matchers, you should use them everywhere, so that all your assertions begin with assertThat(). This will make your tests very readable indeed.

113

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]