Wednesday, February 2, 2011

Use Spring to Wire Up Varargs

This describes a technique to provide N objects to a constructor using Spring. Nothing real new or innovative here; just an idiom I wanted to save for future reference. Let's say we have a constructor that uses varargs:


public MockDao(SummaryData...summaries) {
// save the summary data for downstream use...
}

And, we want to use Spring to provide test summary data to our mocked-out DAO. The summary data objects require a name and a value:


<bean id="mockDAO" class="com.mybiz.dao.MockDao">
<constructor-arg>
<array>
<bean class="com.mybiz.model.SummaryData">
<constructor-arg index="0" value="data-1"/>
<constructor-arg value="25"/>
</bean>
<bean class="com.mybiz.model.SummaryData">
<constructor-arg index="0" value="data-2"/>
<constructor-arg value="447"/>
</bean>
<bean class="com.mybiz.model.SummaryData">
<constructor-arg index="0" value="data-3"/>
<constructor-arg value="-36"/>
</bean>
</array>
</constructor-arg>
</bean>

We can add as many SummaryData beans as needed to the Spring configuration. The mocked-out DAO is intended for use in a test case that we keep separate from the test data; the DAO will e.g. return the mock summary data when the corresponding DAO method is called by the test case. Since the DAO need not go across the wire to e.g. a database, it keeps the test case at unit (vs. integration) level,  allows us to manipulate the data without writing to the database, and in particular allows us to conveniently add comprehensive test data, edge cases, etc. - all without any need to worry about database credentials, database down, etc.

No comments:

Post a Comment