0

Reuse Unit Tests by Converting them to Parameterized Tests

This post demonstrates how to reuse our unit tests with JUnit Parameterized. Let’s say, we have a JUnit test class that tests for, for example, a single web browser’s "browse-to-URL" functionality in various scenarios and we want to reuse those tests for other browsers with the least code change.

JUnit version: 4.12

Unit Tests – Firefox

The following codes uses WebBrowserInterface and WebBrowserFactory. WebBrowserInterface is a common interface that all web browser implements; while WebBrowserFactory instantiates appropriate WebBrowserInterface implementation based on the argument passed to the createImpl method. The argument can be either "firefox", "ie", or "chrome".

Unit Tests – IE

We could copy-paste the codes above and modify them a bit for another browser, e.g., Internet Explorer.

Unit Tests – Chrome

How about the same codes for Chrome? Yes, copy-paste might still work but our unit tests have started exhibit signs to hard-to-maintain codes (at least for unit tests).

Parameterized Tests

We could reduce our duplicate codes by using JUnit Parameterized Tests using org.junit.runners.Parameterized.

All the codes above can be ported to the following codes:

Download the Codes

https://github.com/Turreta/Reuse-Unit-Tests-by-Converting-them-to-Parameterized-Tests