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

import static org.junit.Assume.*;

public class AssumeTest {

@Test

public void shouldRunOnlyOnWindows() { assumeTrue(thisIsAWindowsMachine()); System.out.println("running on Windows!");

}

private boolean thisIsAWindowsMachine() {

return System.getProperty("os.name").startsWith("Windows");

}

@Test

public void shouldRunOnlyOnLinux() { assumeTrue(thisIsALinuxMachine()); System.out.println("running on Linux!");

}

private boolean thisIsALinuxMachine() {

return System.getProperty("os.name").startsWith("Linux");

}

}

Importing of the static methods of the Assume class.

Each test method has a "precondition". If this precondition is not met, then the rest of the test method won’t be executed.

Depending on your operating system you should see only one of these messages.

A sample output from my Linux-powered box:

Test '...chp06.assume.AssumeTest.shouldRunOnlyOnWindows' ignored org.junit.internal.AssumptionViolatedException:

got: <false>, expected: is <true>

at org.junit.Assume.assumeThat(Assume.java:95) at org.junit.Assume.assumeTrue(Assume.java:41)

...

running on Linux!

The Assume class methods are similar to those offered by the Assert class. Please take a look at the JavaDocs to learn about them.

You should only very rarely either ignore tests or just run them under certain conditions. Make sure you have a good reason before doing so!

6.4. More about Expected Exceptions

In Section 3.7 we learned about the default approach to expected exceptions testing with JUnit using the expected attribute of the @Test annotation. In this section we will be discussing this topic in greater detail and showing how certain more complex requirements with regard to exceptions testing can be met. But first, let us remind ourselves of what we have already learned. An example of the default expected exceptions testing pattern is presented below.

104

Chapter 6. Things You Should Know

Listing 6.3. Expected exceptions testing pattern - a reminder

@Test(expected = ExceptionClass.class) public void shouldThrowException() {

//calling SUT's method which should

//throw an exception of ExceptionClass

}

There is no explicit assertion anywhere within the test code regarding the expected exception. Everything is handled through the annotation of the test method.

This pattern has three main disadvantages. Firstly, it does not allow us to inspect all the properties of the exception that has been caught – neither does it allow us to examine the properties of the SUT after the exception has been thrown. Secondly, the use of annotation makes the test code diverge from the usual pattern of arrange/act/assert (or, if you happen to be an advocate of BDD, that of given/when/ then). Thirdly, the test will pass no matter which line of the test or production code thrown the excepted exception.

It is time to learn how to deal with the expected exceptions of some not-so-basic cases.

As was previously mentioned, the rules for specifying expected exceptions in tests are the same as for the catch clause of a try-catch-finally statement: explicitly name the exceptions you expect to catch, and never use general exception classes!

6.4.1. The Expected Exception Message

On some rare occasions it is important to verify whether the exception has been thrown with a proper message or not. This is rarely the case, because the exception message is usually an implementation detail and not something your clients would care about. However, the following case - shown in Listing 6.4 - illustrates the need for exception message verification. It presents a Phone class which verifies numbers passed to it.

Listing 6.4. Phone class method throwing the same exception twice

public class Phone { private String number;

public Phone() {

}

public void setNumber(String number) {

if (null == number || number.isEmpty()) { throw new IllegalArgumentException(

"number can not be null or empty");

}

if (number.startsWith("+")) {

throw new IllegalArgumentException(

"plus sign prefix not allowed, number: [" + number + "]");

}

this.number = number;

}

}

In both cases, IllegalArgumentException is thrown, but with a different message.

8The term "code smell" was coined by Kent Beck; see http://en.wikipedia.org/wiki/Code_smell for more information.

105

Chapter 6. Things You Should Know

The throwing of two exceptions of the same kind could be regarded as being an instance of "code smell"8. It would probably be better if two different exceptions were thrown.

Now imagine a test method that verifies the expected exception thrown by the setNumber() method of the Phone class. Relying solely on the exception type (in this case IllegalArgumentException) will not suffice this time.

The first thing we might do is revert to an old method of exception testing - one which uses a trycatch statement.

Listing 6.5. setNumber() method test with try/catch

Phone phone = new Phone();

@Test

public void shouldThrowIAEForEmptyNumber() { try {

phone.setNumber(null);

fail("Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException iae) {

assertEquals("number can not be null or empty", iae.getMessage());

}

}

@Test

public void shouldThrowIAEForPlusPrefixedNumber() { try {

phone.setNumber("+123");

fail("Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException iae) {

assertEquals("plus sign prefix not allowed, " + "number: [+123]", iae.getMessage());

}

}

We expect the setNumber() method to throw an exception of the InvalidArgumentException type. If we have reached this point, then it means the expected exception has not been thrown – so it is time to fail the test (using a static fail() method of the Assert class).

Inside the catch block we can verify the exception message.

Using the try-catch statement, we can test the message of a thrown exception, or its other properties (e.g. the root cause). But we can surely all agree that it is hard to be proud of such test code. The flow of the test is obscured by the try-catch statement, the swallowed exception in the catch block is something that makes me feel uneasy every time I see it, and the use of fail() as an "inverted" assertion looks strange. If only we could get rid of this try-catch

6.4.2. Catch-Exception Library

Listing 6.6 proves that it is possible to get rid of the try-catch statement while still being able to verify whatever we want, and to do all this adopting a nice, clean arrange/act/assert approach. It uses an additional library - Catch-Exception9 by Rod Woo, which provides some convenient methods for dealing with expected exceptions in test code.

9See http://code.google.com/p/catch-exception/

106

Chapter 6. Things You Should Know

Listing 6.6. Expected exceptions testing - BDD style

import static com.googlecode.catchexception.CatchException.*;

...

Phone phone = new Phone();

@Test

public void shouldThrowIAEForEmptyNumber() { catchException(phone).setNumber(null);

assertTrue(caughtException() instanceof IllegalArgumentException); assertEquals("number can not be null or empty",

caughtException().getMessage());

}

@Test

public void shouldThrowIAEForPlusPrefixedNumber() { catchException(phone).setNumber("+123");

assertTrue(caughtException() instanceof IllegalArgumentException); assertEquals("plus sign prefix not allowed, " +

"number: [+123]", caughtException().getMessage());

}

Importing of static methods of the CatchException class from the Catch-Exception library.

The static method catchException() of the CatchException class is used to call a method which is expected to throw an exception.

The thrown exception is returned by another static method (caughtException()). The assertion verifies whether an appropriate exception has been thrown.

The exception message is likewise verified.

The code in Listing 6.6 fits nicely into arrange/act/assert. It is concise and highly readable. The static methods of the Catch-Exception library make the sequence of the code easy to grasp. Since the caught exception is available after it has been thrown (you can assign it to some variable, e.g. Exception e = caughtException()), it is possible to analyze some of its properties. In addition, if some of the methods executed within the test method are capable of throwing the same exception, a developer can specify which of them is expected to do so by wrapping specific lines of code with the catchException() method. Thanks to this, no mistakes concerning the provenance of the caught exception are possible.

6.4.3. Testing Exceptions And Interactions

Another case where catching expected exceptions with the expected attribute of the @Test annotation is not sufficient is when there is more to be verified than just whether an appropriate exception has in fact been thrown or not. Let us consider the following example:

107

Chapter 6. Things You Should Know

Listing 6.7. Code to be tested for exceptions and interaction

public class RequestHandler {

private final RequestProcessor requestProcessor;

public RequestHandler(RequestProcessor requestProcessor) { this.requestProcessor = requestProcessor;

}

public void handle(Request request) throws InvalidRequestException { if (invalidRequest(request)) {

throw new InvalidRequestException();

}

requestProcessor.process(request);

}

private boolean invalidRequest(Request request) {

...

// some reasonable implementation here

}

}

Method to be tested. This verifies an incoming request and throws an exception, or asks a collaborator - requestProcessor - to process it.

Now let us assume that we want to check to make sure that if an invalid request arrives, it is NOT then passed to requestProcessor, and that the appropriate exception is thrown. In such a case we will need to use a different pattern. One possibility is to follow the normal approach to exceptions handling, based on a try-catch statement. But we already know that this makes test code obscure. Let us use the CatchException library once again.

Listing 6.8. Expected exceptions testing - BDD style

@Test

public void shouldThrowExceptions() throws InvalidRequestException { Request request = createInvalidRequest();

RequestProcessor requestProcessor = mock(RequestProcessor.class); RequestHandler sut = new RequestHandler(requestProcessor);

catchException(sut).handle(request);

assertTrue("Should have thrown exception of InvalidRequestException class", caughtException() instanceof InvalidRequestException);

Mockito.verifyZeroInteractions(requestProcessor);

}

The static method catchException() of the CatchException class is used to call a method which is expected to throw an exception.

The thrown exception is returned by another static method (caughtException()). The assertion verifies whether an appropriate exception has been thrown.

We are making sure that the invalid request has not been passed to requestProcessor. We have already seen how Mockito can verify that a specific method has not been called on a mock object (with the never() method - see Section 5.4.3). Another Mockito method - verifyZeroInteractions() - is more general in scope: it verifies whether any calls have been made to some given test doubles, and fails the test if they have.

108

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