Example: Data Providers
Let’s revisit testing the reduce method of class Fraction. Did you notice that all of those methods were basically the same? The only difference was the values used to initialize the Fraction object. Instead of writing four different methods, we can write a single method and use a Data Provider to call the method with different values. A DataProvider is a method that defines the data that you want to pass into the test method. Your test method will be called exactly once for each set of data.
The following two methods do exactly the same thing as the testReduce methods that were shown earlier. The trade off is that if one of the method calls fails, you have to dig into the values of the parameters to figure out which case failed. You can avoid this by adding another parameter to assertEquals. The last parameter is a String that is displayed if the assertion fails.
/** * The DataProvider method * * Returns a 2D array in which each row contains the arguments to be passed * to the test method */ @DataProvider(name = "getFractionValues") public Object[][] getFractionValues() { // Each row needs to contain int numerator, int denominator, int expectedNumerator, int expectedDenominator // which matches the parameters of the test method return new Object[][] { { 7, 15, 7, 8, "Already reduced fraction" }, // reduced fraction data { 18, 3, 6, 1, "Improper Fraction" }, // improper fraction data { 2, 4, 1, 2, "Quickly reducible data" }, // quick reduce fraction data { 405, 450, 9, 10, "Slower reducible data" } // slow reduce fraction data }; } /** * Test method that uses the data provider * * Specify the name of the data provider (as defined by the name attribute, not * the name of the method) */ @Test(dataProvider = "getFractionValues") public void testReduce(int numerator, int denominator, int expectedNumerator, int expectedDenominator) { Fraction testObj = new Fraction(numerator, denominator); assertEquals(testObj.getNumerator(), expectedNumerator); assertEquals(testObj.getDenominator(), expectedDenominator); }
The data provider method returns a 2D array of Objects. Remember that all Java classes inherit from Object, so this array can hold anything. Each row in the array contains the arguments to be passed into the test method.
In the example above, the following method calls are generated and run:
testReduce(7, 15, 7, 15, "Already reduced fraction");
testReduce(18, 3, 6, 1, "Improper Fraction");
testReduce(2, 4, 1, 2, "Quickly reducible data");
testReduce( 405, 450, 9, 10, "Slower reducible data");