我在我的测试框架中使用 Spring 自动扫描组件。
Autowired 在所有类中都可以正常工作,除了扩展 Junit Testwatcher 的类。
我扩展 Junit testwatcher 的类是:
@Component
public class PrintTrace extends TestWatcher{//this class overrides pass and fail
//methods in Testwatcher
@Autowired
private HTMLLogger htmlLogger //this is null all the time. it works in
//other classes
}
我的基类看起来像:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class YahooTestSetUp {
public static WebDriver driver;
@Rule
public PrintTrace printTrace = new PrintTrace();
@Autowired
private HTMLLogger htmlLogger;//here its working fine
}
还有我的 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pilz"/>
</beans>
请建议这对我来说非常重要。否则我应该选择单例对象,这对我来说不是一个好的解决方案。
添加更多信息:
假设我有 2 个测试套件,它们访问 2 个通用类 HTMLLogger.class 和 PrintTraece.class。
每个测试套件都独立于其他套件。这些套件有@BeforeClass 和@AfterClass
见下文:
@RunWith(Suite.class)
@Suite.SuiteClasses({ AutowireClass.class})
public class YahooTestSuite extends YahooTestSetUp{
private static HTMLLogger htmlLogger;
@BeforeClass
public static void allTests() throws Exception {**//Can I use @Autowired in
static methods(no)**
htmlLogger = new HTMlLogger()
htmlLogger.createHTMLLogFile();
}
@AfterClass
public static void afterAll() throws Exception{
htmlLogger.htmlLogEnd();
}
}
另一个套件对其他模块做同样的事情。
正如我之前所说,我的 PrintTrace.class extends Testwatcher.class(Junit rule) 它看起来像
使用基类中创建的规则调用此类。
@Component
public class PrintTrace extends TestWatcher{
private HTMLLogger htmlLogger = null;
@Override
public void starting(final Description description) {
}
@Override
public void failed(final Throwable e, final Description description) {
htmlLogger.writeFailLog();**//This is common for all suites**
//This should be same object used in suite
}
@Override
public void succeeded(final Description description) {
htmlLogger.writePassLog();//This is common for all suites
//This should be same object used in suite
}
@Override
public void finished(Description description) {
}
谢谢