0

我正在尝试运行一个简单的测试来检查我保存在我的 Maven 项目的 src/test/resources 文件夹中的属性文件中的值,但是 JUnit 测试失败了。我的测试正在拾取文件 OK,但它没有返回预期值,因为文件看起来不像正在加载。还有其他人有类似的问题吗?我的代码/测试如下:

我的应用程序上下文文件:

<bean id="myProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:test.properties"/>
</bean> 

我的代码:

@Resource(name = "myProps") private Properties myProps;
@Value("#{myProps['totalNumberOfChanges']}") private String totalNumberOfChangesStr;
@Value("#{myProps['delayTime']}") private String delayTimeStr;

    public void parseAttributesFromConfigFile() {
        String methodName = "parsePropertyAttributesFromConfigFile";
        try {
            totalNumberOfChanges = Integer.parseInt(totalNumberOfChangesStr);
            delayTime = Integer.parseInt(delayTimeStr);
            numEntriesToIterateThru = (totalNumberOfChanges / delayTime);
        } catch (NumberFormatException nfe) {
            LOGGER.error(methodName, "", "Number Format Exception Occured" + nfe.getMessage());
        }
    }

我的 Junit 测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/Testpu.xml" })
public class ConfigPropertiesTest {
    private final int NUM_ENTRIES_TO_ITERATE_THRU = 100;
    private final int TOTAL_NUMBER_OF_CHANGES = 100000;
    private final int DELAY_TIME = 1000;

    private ConfigProperties configProperties;

    @Before
    public void setUp() throws Exception {
        configProperties = new ConfigProperties();
    }

    @Test
    public final void testParseAttributesFromConfigFileIsCalled() {
        configProperties.parseAttributesFromConfigFile();

        int numEntriesToIterateOver = configProperties.getNumEntriesToIterateThru();
        assertEquals(numEntriesToIterateOver, NUM_ENTRIES_TO_ITERATE_THRU);

        int numberOfChanges = configProperties.getTotalNumberOfChanges();
        assertEquals(numberOfChanges, TOTAL_NUMBER_OF_CHANGES);

        int delayTime = configProperties.getDelayTime();
        assertEquals(delayTime, DELAY_TIME);
    }
}
4

1 回答 1

0

您正在您的方法中创建ConfigPropertiesBefore。如果要Spring基于注释填充值,则必须将 bean 创建为 Spring 上下文的一部分。如果您的ConfigPropertiesSpring 上下文中有一个实例,请使用将该实例加载到您的测试中@Autowired

于 2013-06-13T16:02:26.697 回答