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

Chapter 6. Things You Should Know

Listing 6.48. Detailed error message of Hamcrest collections assertions

java.lang.AssertionError:

Expected: a collection containing "xyz" got: <[s1, s2]>

6.12.3. Custom Solution

If your needs with regard to collection testing are so specific that none of the previously presented solutions are good enough, then you will have no choice but to come up with your own solution. You will have at least two options for how to proceed:

write utility methods which will do collections verification as you require it to be done,

create custom matchers - see Section 6.6.

The first option is faster to implement, but it does not add to the readability of tests. Matchers require some additional work, but they offer greater reusability and a nice testing DSL25, which gives very readable assertions.

6.12.4. Conclusions

In this section, various ways of testing collections have been discussed. Examples of Unitils, FEST Fluent Assertions and Hamcrest have been given, along with brief information about other features of these libraries. Finally, we have taken a look at custom solutions.

In conclusion, if your tests involve a great deal of collections testing, I would suggest investing time in mastering one of the libraries presented in this section. FEST Fluent Assertions seems to me the best choice (when it comes to collection testing), because it provides a lot of useful assertions and is very extensible, so you can also add your own if required.

6.13. Reading Test Data From Files

A commonly arising issue concerns the reading of data for tests from CSV or Excel files. This is especially important if the data has been provided by someone else (e.g. QA people, or maybe even your client). The likelihood of them using Excel (or its Open/LibreOffice counterparts) is quite high.

Of course, it is possible to come up with a custom solution and leverage libraries like OpenCSV26, SuperCSV27, Apache POI28 or JExcelApi29. These libraries help you to read data from CSV and Excel files – but still, we would need to use them within our test code. This is neither hard, nor time consuming, but since we have some ready solutions, let us have a look at them.

For both CSV and Excel files we will use the same test case: to verify whether our software calculates valid discounts based on the total value of a purchase made by a client.

25DSL - Domain Specific Language, http://en.wikipedia.org/wiki/Domain-specific_language 26http://opencsv.sourceforge.net/

27http://supercsv.sourceforge.net/

28http://poi.apache.org/

29http://jexcelapi.sourceforge.net/

138

Chapter 6. Things You Should Know

6.13.1. CSV Files

As for the CSV files, we can make use of what the JUnitParams library offers. Up to now we have been using its @Parameters annotation with the method attribute, to point out a method responsible for providing test data. This time we will use another annotation - @FileParameters - in order to use a CSV file as a test data reservoir.

First of all, we need a CSV file with test data. Every row should contain a set of data (in our case, this will be purchase value and percentage discount) separated by a comma. An example is given below:

financial.csv.

value,discount

0.00,0

999.99,0

1000.00,0.01

1999.99,0.01

2000.00,0.02

2999.99,0.02

5000.00,0.03

10000.00,0.03

378433.00,0.03

A header which will be ignored.

Now, we want to test whether the DiscountCalculator class, when given the first value from a row, returns a discount equal to the second value from the same row.

Listing 6.49. Reading test data from CSV file

import junitparams.FileParameters; import junitparams.JUnitParamsRunner;

import junitparams.mappers.CsvWithHeaderMapper; import org.junit.Test;

import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

@RunWith(JUnitParamsRunner.class) public class ReadCSVJUnitParamsTest {

@Test

@FileParameters(value = "classpath:financial.csv", mapper = CsvWithHeaderMapper.class)

public void shouldCalculateDiscount(double value, double discount) { assertEquals(discount,

DiscountCalculator.calculateDiscount(value), 0.0001);

}

}

Importings as required, including the @FileParameters annotation and the CsvWithHeaderMapper class.

We need to tell JUnit that we will be using a specialized runner (as we have always done when using JUnitParams).

The @FileParameters annotation allows us to specify the data file and mapping class.

The data from the CSV file will be automatically cast to proper types (double in this case).

139

Chapter 6. Things You Should Know

And that is it! All we have to do now is run the test.

JUnitParams also allows to specify an absolute path (e.g. /home/mynick/data/testdata.csv). As usual when pointing to files make sure you do not make a typo providing their name and/ or path!

6.13.2. Excel Files

Like with CSV, there are many ways to read test data from an Excel file. For example, one could write a custom implementation of the DataMapper class (part of the JUnitParams library), and use it exactly as we have used the CsvWithHeaderMapper class in the previous example. In this section I would like to present another solution based on annotations provided by another useful library: the EasyTest project.

Let us start with an Excel file which contains the test data. The first column of this file is required by the EasyTest library, and must be identical to the name of a test method that is going to use the data from this file.

Figure 6.1. Excel data file (created with LibreOffice)

The EasyTest project offers more than this: for example, it is possible to have data for many test methods within one Excel file. Please read EasyTest’s documentation to learn more.

The following listing shows how to read test data from this Excel file using annotations provided by the EasyTest project. As you can see, the test method is named shouldCalculateDiscount(), which is exactly the same name that appeared in the Excel file.

140

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