Case Study

Testing the Domain Model

Previous Next
The domain model of the case study is composed of POJOs and testing it with SpringUnit requires merely applying the approach already demonstrated in the User Documentation Tutorial. We can begin by writing a test for the setName method of the Product class. First, we need a class ProductTest that extends SpringUnitTest. Next, we need a Spring configuration file called ProductTest.xml that holds a bean of type SpringUnitContext and whose ID is productTest. The ProductTest class needs a property called productTest of type SpringUnitContext. Finally, we can write the code for the test of the method. First we obtain a Product object from the SpringUnitContext, along with the input value for the product's name, and the expected value. Next, we call the setName method with the input value, read back that value and compare it with the expected value. The following code excerpts show all of this. Product.java (excerpt)
public class Product /* ... */ {
	/* other methods not shown */
	public void setName(String name) {
		this.name = name;
	}
	private String name;
	/* other fields not shown */
}
ProductTest.java (excerpt)
public class ProductTest extends SpringUnitTest {
	/* other test methods not shown */
	public void testName() throws Exception {
		Product subject = getObject("subject");
		String name = getObject("name");
		String expected = getObject("expected");
		subject.setName(name);
		String actual = subject.getName();
		assertTrue(expected.equals(actual));
	}
	/* setter/getter not shown */
	private SpringUnitContext productTest;
}

ProductTest.xml (excerpt)

<beans>
	<import resource="classpath:ProductData.xml"/>
	<bean id="productTest" class="org.springunit.framework.SpringUnitContext">
		<property name="data">
			<map>
				<entry key="testName">
					<map>
						<entry key="subject">
							<ref bean="product1"/>
						</entry>
						<entry key="name">
							<value>tuna feast</value>
						</entry>
						<entry key="expected">
							<value>tuna feast</value>
						</entry>
					</map>
				</entry>
				<!-- other entries omitted -->
			</map>
		</property>
	</bean>
</beans>

Previous Next