Question

I just found a TestNG test case that uses Spring to provide its data source. As a result the code is quite clean and concise.

However, I need to expand the test cases so they can take a variable list of inputs.

Am I stuck using bean references for the list of lists as I've attempted below? Is there a way to do that and still be pretty (i.e. not breaking up the logical flow of input followed by output)? Is there a better way?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="stringPatternRegexMap" class="java.util.HashMap">
        <constructor-arg>
            <map>
                <entry key="some input #1" value="expected output #1"/>
                <entry key="some input #2" value="expected output #2"/>
                <entry key="some input #3" value="expected output #3"/>
                <entry key-ref="multi-list-1" value="expected output #3"/>
                <entry key-ref="null-reference" value="null-reference"/>
            </map>
        </constructor-arg>
    </bean>

    <bean id="multi-list-1">
            <list>
                    <value>apple</value>
                    <value>banana</value>
                    <value>orange</value>
            </list>
    </bean>

    <bean id="null-reference">
            <value>
                    <null/>
            </value>
    </bean>
</beans>

Note that the original code appears to be using a map instead of a list because it seems an easier way to provide a list of String[2].

Was it helpful?

Solution

No, you can use a @DataProvider to feed a test methods with a variable number of parameters:

  @DataProvider
  public Object[][] dp() {
    return new Object[][] {
        new Object[] { new Object[] { "a" } },
        new Object[] { new Object[] { "b", "c" } },
    };
  }

  @Test(dataProvider = "dp")
  public void g1(Object... params) {
    System.out.println("Received " + params.length + " parameters");
  }

will print:

Received 1 parameters
Received 2 parameters

Note that your test method can declare either "Object..." or "Object[]" (it's the same to the compiler).

OTHER TIPS

I would use TestNG and its DataSource construct as the right way to do this. You certainly can make this Spring configuration, but since it's test code I think TestNG is the more natural home for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top