我正在尝试运行一个简单的测试来检查属性文件中的值,该文件已保存在我的Maven项目的src / test / resources文件夹中,但JUnit测试失败了。我的测试是拿起文件确定但它没有返回预期的值,因为文件看起来不像它被加载。其他人有类似的问题吗?我的代码/测试如下:
我的应用程序上下文文件:
<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);
}
}
答案 0 :(得分:0)
您正在ConfigProperties
方法中创建Before
课程。如果希望Spring
基于注释填充值,则必须将bean创建为Spring上下文的一部分。如果您的Spring上下文中有ConfigProperties
的实例,请使用@Autowired
将该实例加载到您的测试中