テスト フレームワークで 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 つの共通クラス HTMLLogger.class と PrintTrace.class にアクセスする 2 つのテスト スイートがあるとします。
各テストスイートは、他のスイートから独立しています。これらのスイートには @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 は Testwatcher.class(Junit ルール) を拡張します。
このクラスは、ベースクラスで作成されたルールで呼び出されます。
@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) {
}
ありがとう