Common Errors in SpringUnit Tests

Incorrect Type of Value in XML Configuration File

Description

A SpringUnit test fails because the type of a value referenced within a test in the Java source code does not match the type of the value declared in the XML configuration file.

Symptoms

java.lang.ClassCastException: java.lang.String
    at org.springunit.examples.errors.IncorrectTypeOfValueInXmlTest.testOne(IncorrectTypeOfValueInXmlTest.java:9)
    ...

Cause

This error occurs when the type of a value referenced in a test method in the Java source code does not match the type declared in the XML configuration file. This typically results in ClassCastExceptions.

Remedy

Change the type of the value in the XML configuration file, or in the Java source code.

Example

Java Source Code:
package org.springunit.examples.errors;

import org.springunit.framework.SpringUnitContext;
import org.springunit.framework.SpringUnitTest;

public class IncorrectTypeOfValueInXmlTest extends SpringUnitTest {
    
    public void testOne() throws Exception {
        int i = getObject("i");
        int expected = getObject("expected");
        assertEquals(expected, i);
    }
    
    public SpringUnitContext getIncorrectTypeOfValueInXmlTest() {
        return incorrectTypeOfValueInXmlTest;
    }

    public void setIncorrectTypeOfValueInXmlTest(
            SpringUnitContext incorrectTypeOfValueInXmlTest) {
        this.incorrectTypeOfValueInXmlTest = incorrectTypeOfValueInXmlTest;
    }

    private SpringUnitContext incorrectTypeOfValueInXmlTest;

}
XML Configuration File:
<beans>

    <bean id="incorrectTypeOfValueInXmlTest" class="org.springunit.framework.SpringUnitContext">
        <property name="data">
            <map>
                <entry key="testOne">
                    <map>
                        <entry key="i"><value>1</value></entry>
                        <entry key="expected"><value type="int">1</value></entry>
                    </map>
                </entry>
            </map>
        </property>
    </bean>
    
</beans>
Previous