我和春天3.0和JUnit 4.8工作时,我试图开发一些单元测试。春天依赖注入空运行测试用例
其实,我只是想设置使用依赖注入的测试用例通过了JUnit使用的应用程序上下文加载XML definined一个bean的属性(文件)。
我使用的注释为JUnit 4中的形式给出了加载XML文件配置。这是主要的BaseTest所使用的所有测试类:
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@Ignore
public class BaseTest { ... }
这是的test-context.xml
<context:component-scan base-package="com.test" />
<bean id="ExtractorTest" class="com.test.service.ExtractorTest">
<property name="file" value="classpath:xls/SimpleFile.xls"></property>
</bean>
一个部分,因此我想要在我的课上做与测试(ExtractorTest
)只是通过在类路径中加载文件来设置'文件'属性,没有别的。
下面是测试类的部分:
public class ExtractorTest extends BaseTest {
private Resource file;
private InputStream is;
public void setFile(Resource file) {
this.file = file;
}
@Before
public void init() {
this.is = this.getClass().getResourceAsStream("/xls/SimpleFile.xls");
Assert.assertNotNull(is);
}
@Test
public void testLoadExcel() throws IOException {
// file is always null, but the InputStream (is) isn't!
Assert.assertNotNull(file.getFile());
InputStream is = new FileInputStream(file.getFile());
HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
// todo...
}
}
的问题是,二传手的作品,因为我已经添加了一个断点,春天正在建立它的性质确定。但是当测试方法开始时它是空的,可能是因为它是另一个正在运行的实例,但为什么?我如何设置要使用应用程序上下文的XML进行测试的'文件'加载?我无法使用jUnit分配它,但我不明白为什么以及如何去做。我试图避免在@Before方法写的,但我不知道它绝对是一个好办法...
谢谢。
PD:对不起我的英语;-)
谢谢阿龙! 这就像你说的。我不知道这是不是使用Spring和jUnit测试文件的最佳方法,因为它代表了很多新的bean来定义(每个测试文件使用1个),但它是有效的。可能是更好的主意,可以在@Before方法中指定它... 无论如何,再次感谢你! – 2012-08-02 15:36:02