Software Development

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".

[wp_ad_camp_2]

Unit Tests – IE

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

[wp_ad_camp_3]

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).

[wp_ad_camp_4]

Parameterized Tests

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

[wp_ad_camp_1]

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

Download the Codes

[wp_ad_camp_5]

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

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like