JUnit4 Parameterized and Theories Examples

I always relied on TestNG to pass parameters to test methods in order to give a bit of flexibility to my tests or suites.

However, the same flexibility can be achieved using JUnit4.

To use it it’s simple:
 
 
 
 
 
 
 

package com.marco.test;

import java.util.Arrays;

import java.util.Collection;

import junit.framework.Assert;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.junit.runners.Parameterized;

import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)

public class ParameterizedTest {

@Parameters

public static Collection data() {

return Arrays.asList(new Object[][] {

/* Sport Nation year totWinners */

{ “basket”, “usa”, 2002, 5, },

{ “soccer”, “argentina”, 2003, 2 },

{ “tennis”, “spain”, 2004, 10 },

{ “chess”, “ireland”, 2005, 0 },

{ “eatingbananas”, “italy”, 2006, 20 }

});

}

private final String sport;

private final String nation;

private final int year;

private final int totWinners;

public ParameterizedTest(String sport, String nation, int year, int totWinners) {

this.sport = sport;

this.nation = nation;

this.year = year;

this.totWinners = totWinners;

}

@Test

public void test() {

Assert.assertTrue(isDataCorrect(sport, nation, year, totWinners));

}

private boolean isDataCorrect(String sport2, String nation2, int year2, int totWinners2) {

return true;

}

}

JUnit will create an instance of the ParameterizedTest class and run the testCombination() method (or any method marked as @Test) for each row defined in the static collection.

Theories

This another interesting feature from JUnit4 that I like. You use Theories in JUnit 4 to test combinations of inputs using the same test method:

package com.marco.test;

import static org.hamcrest.CoreMatchers.is;

import java.math.BigDecimal;

import org.junit.Assert;

import org.junit.Assume;

import org.junit.experimental.theories.DataPoint;

import org.junit.experimental.theories.Theories;

import org.junit.experimental.theories.Theory;

import org.junit.runner.RunWith;

@RunWith(Theories.class)

public class TheoryTest {

@DataPoint

public static int MARKET_FIRST_GOALSCORERE_ID = 2007;

@DataPoint

public static int MARKET_WDW_ID = 2008;

@DataPoint

public static BigDecimal PRICE_BD = new BigDecimal(6664.0);

@DataPoint

public static double PRICE_1 = 0.01;

@DataPoint

public static double PRICE_2 = 100.0;

@DataPoint

public static double PRICE_3 = 13999.99;

@Theory

public void lowTaxRateIsNineteenPercent(int market_id, double price) {

Assume.assumeThat(market_id, is(2008));

Assume.assumeThat(price, is(100.0));

// run your test

Assert.assertThat(price, is(100.0));

}

@Theory

public void highTaxRateIsNineteenPercent(int market_id, double price) {

Assume.assumeThat(market_id, is(2007));

Assume.assumeThat(price, is(13999.99));

Assert.assertThat(price, is(13999.99));

}

@Theory

public void highTaxRateIsNineteenPercent(int market_id, BigDecimal price) {

Assume.assumeThat(market_id, is(2007));

Assert.assertThat(price, is(BigDecimal.valueOf(6664)));

}

}

This time you need to mark the test class as @RunWith(Theories.class) and use @DataPoint to define properties that you want to test.

JUnit will call the methods market as @Theory using all the possible combinations based on the DataPoint provided and the type of the variable. PRICE_BD DataPoint will be used only in the last method, the only one accepting BigDecimal in its method parameters.

Only parameters that satisfy the Assume.assumeThat() condition will make through the asser test. The combinations that don’t satisfy the Assume.assumeThat() condition will be ignored silently.
 

Reference: JUnit4 Parameterized and Theories from our JCG partner Marco Castigliego at the Remove duplication and fix bad names blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

One Response to "JUnit4 Parameterized and Theories Examples"

Leave a Reply


four × 3 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books