Добавил:
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

Listing 6.17. Use of Hamcrest matchers with Mockito

import static org.mockito.Matchers.argThat; import static org.hamcrest.Matchers.hasEntry;

User user = new User();

UserDAO userDAO = mock(UserDAO.class);

when(userDAO.getUserByProperties((Map<String, String>) argThat(hasEntry("id", "2")))).thenReturn(user);

assertNull(userDAO.getUserByProperties(new HashMap<String, String>()));

Map<String, String> properties = new HashMap<String, String>(); properties.put("id", "2");

assertEquals(user, userDAO.getUserByProperties(properties));

The necessary static methods are imported.

Our use of the Hamcrest matcher hasEntry() must be wrapped in the argThat() method of Mockito11.

This map does not fulfill the requirement - no user will be returned (as discussed previously, Mockito will return null in such cases).

Now the map contains the entry required by the matcher, so a real user will be returned.

"Limitless possibilities" are opened up, in that it is possible to write custom Hamcrest matchers that can then be used within the argThat() method in just the same way as the original Hamcrest matchers are used.

6.7.2. Matchers Warning

One thing to remember is that if you are using argument matchers, all arguments have to be provided by matchers. This is shown in Listing 6.18 (an example copied directly from the Mockito documentation):

Listing 6.18. The requirement to use matchers for all arguments

verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));

verify(mock).someMethod(anyInt(), anyString(), "third argument");

This is correct: all argument are matchers.

This is incorrect: the third argument is not a matcher and will result in an exception being thrown.

6.8. Rules

We have already learned about the @Before and @After annotations, which are very handy for doing things before and after test methods are executed. Apart from them, JUnit offers a more flexible mechanism, which can replace these annotations and which also allows you to do things that lie beyond their capacities.

11This is because all Hamcrest matcher methods return objects of the org.hamcrest.Matcher<T> type, while Mockito matchers return objects of the T type.

116

Chapter 6. Things You Should Know

One could compare JUnit rules to aspect-oriented programming12. With the use of annotations, they can be declared in just one place but applied to many tests. There is no need to repeat the same code in many places or use inheritance.

The functionality discussed in this chapter is rarely used in unit tests. Still, it is indispensable in some cases, so we should learn about those too.

JUnit allows you to write rules which affect test classes or test methods. Both are written and used in a very similar way. A custom rule which is supposed to work at the class level should implement the TestRule interface. A custom rule intended to work for test methods should implement the MethodRule interface. When browsing JUnit’s JavaDocs one can learn that there are already several rules available. All of them are listed below:

ErrorCollector: collect multiple errors in one test method13,

ExpectedException: make flexible assertions about thrown exceptions,

ExternalResource: start and stop a server, for example,

TemporaryFolder: create fresh files, and delete after test,

TestName: remember the test name for use during the method,

TestWatcher: add logic at events during method execution,

Timeout: cause test to fail after a set time,

Verifier: fail test if object state ends up incorrect.

It would definitely be worth your while to take a closer look at these rules. Please read the appropriate JUnit JavaDocs.

6.8.1. Using Rules

The best way to learn how to use rules is to see them in action. Let us take one of the rules provided by JUnit as an example.

12http://en.wikipedia.org/wiki/Aspect-oriented_programming

13Descriptions were copied directly from JUnit JavaDocs.

117

Chapter 6. Things You Should Know

Listing 6.19. Use of a rule

import org.junit.Rule; import org.junit.rules.Timeout;

public class TimeoutTest {

@Rule

public Timeout globalTimeout = new Timeout(20);

@Test

public void willFail() throws InterruptedException { Thread.sleep(100);

}

@Test

public void willPass() throws InterruptedException { Thread.sleep(10);

}

}

The @Rule annotation tells JUnit to apply the Timeout rule to all test methods of this class. The rule used in the test must be instantiated.

Nothing special here. However, the Timeout rule will stop any test which takes longer than 20 milliseconds and mark it as failed.

This example shows how to use a rule that is applied to every test method of a given class. We will soon see that some rules can also work when applied only to selected methods.

6.8.2. Writing Custom Rules

There are many requirements that could be addressed by writing custom rules. Their power lies in the fact that they can be used to modify the tests or the environment (e.g. the file system) during their execution. A typical use for the rules is to implement the retry functionality. By retry I mean the possibility of rerunning a failed test and marking it as passed if it succeeds during this second execution.

Such functionality is mainly useful for integration or end-to-end tests which rely on some external entities (outside of our control). Then, in some cases, it makes perfect sense to try to execute the same test again, in the hope that this time these external entities will work properly and the test will pass. When working with unit tests you will rarely, if ever, have a need for such a functionality. Personally, I have only ever used it to test some probabilityrelated code.

There are two JUnit types that we need to get familiar with to accomplish the task:

TestRule - an interface, with a single apply() method. This is our entry point into the world of rules.

Statement - an abstract class. We need to implement its child class and override its evaluate() method.

Once again we will let the code speak. This time we shall start with the final effect: our custom rule in action. The expected behaviour of this test is that the shouldBeRerun() test method will fail during the second execution. We will be in a position to observe this thanks to the executionNumber variable, which is incremented every time this method is executed.

118

Chapter 6. Things You Should Know

Listing 6.20. Custom rule in action

public class RetryRuleTest {

@Rule

public RetryTestRule retryTestRule = new RetryTestRule();

static int executionNumber = 0;

@Test

public void shouldBeRerun() { executionNumber++;

System.out.println("execution: " + executionNumber); Assert.fail("failing: " + executionNumber);

}

}

Just as with the rules provided by JUnit, we need to instantiate them (i.e. mark the public modifier!).

Some information is printed, so it is possible to witness the progress of the test (i.e. its second execution).

This test should fail with a failing: 2 error message.

Now we know where we are heading, we must figure out how to get there. The next listing shows the code of the RetryTestRule custom rule class.

This class will be used automatically by JUnit (once instantiated, as shown in Listing 6.20). The base object of the Statement type will be injected by JUnit to the apply() method during test execution. This object will contain information about the test method being executed.

Listing 6.21. A custom rule

import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement;

public class RetryTestRule implements TestRule {

@Override

public Statement apply(final Statement base, final Description description) {

return new Statement() { @Override

public void evaluate() throws Throwable { try {

base.evaluate(); return;

} catch (AssertionError ae) { base.evaluate(); return;

}

}

};

}

}

Required imports.

Our custom rule must implement the TestRule interface and implement its single apply() method.

119

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