4

tomcat 7でWebアプリを実行すると、デプロイメント記述子に2つのリスナーが含まれます。1つは作成したカスタムリスナーで、もう1つはSpringのリスナーです。

<listener>
    <listener-class>com.company.appName.web.context.MyContextListener</listener-class>
</listener>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

統合テストを実行しているとき、リスナーはまったく呼び出されないので、それを克服するために、自分で初期化を行っています(基本的にこのリスナーから呼び出される静的メソッドを呼び出します)。とにかく、私はここで何かが欠けていると思います、リスナーはいつ呼ばれますか?統合テスト中にgetが初期化されないのはなぜですか?具体的には、Springコンテキストは初期化されます。これは、テストクラスの最上位で宣言しているためです。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:testApplicationContext.xml" })

したがって、web.xmlが実際に使用されることはありません。

この場合、Springコンテキストが常に最初に呼び出され、初期化される前に何もする機会がありません-そうですか?Springのコンテキストの前にコードを実行する方法はありますか?

更新:テストスイートで@BeforeClassアノテーションを使用していることにも言及したいと思います。

@RunWith(Categories.class)
@IncludeCategory(HttpTest.class)
@SuiteClasses({ <MY TEST CLASSES> })
public class HttpSuiteITCase {

    /**
     * Run once before any of the test methods.
     */
    @BeforeClass
    public static void setTestsConfigurations() {
    TestConfiguration.setup(false);
    }
}

このアプローチを使用しても問題は解決しません。テストクラスとすべてのSpringBeanが最初に初期化されます。

前もって感謝します

4

2 に答える 2

3

staticテストクラスのメソッドに注釈を付け、@BeforeClassそこで初期化を行います。例えば:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:testApplicationContext.xml" })
public class TestTest {

    @BeforeClass
    static public void beforeClass() {
        // do intialization here
    }

初期化コードがクラスフィールドにアクセスする必要があるためにアクセスできない場合はstatic、代わりにを設定してTestExecutionListener実装できbeforeTestClass()ます。例については、このブログ投稿を参照してください。

于 2012-07-23T02:32:51.610 に答える
0

テストコンテキストで、Beanでinit-methodを使用することで実行できます。

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

パブリッククラスExampleBean{

public void init() {
    // do some initialization work
}

}

于 2012-07-23T04:02:16.757 に答える