8

Spring 3.1.2、JUnit 4.10.0を使用しており、両方のバージョンでかなり新しい。注釈ベースの自動配線を機能させることができないという問題があります。

以下は2つのサンプルで、1つは注釈を使用しておらず、正常に機能しています。そして2つ目は注釈を使用していますが、これは機能しません。理由はわかりません。私はspring-mvc-testのサンプルにほぼ従っています。

働く

package com.company.web.api;
// imports

public class ApiTests {   

    @Test
    public void testApiGetUserById() throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/com/company/web/api/ApiTests-context.xml");
        UserManagementService userManagementService = (UserManagementService) ctx.getBean("userManagementService");
        ApiUserManagementController apiUserManagementController = new ApiUserManagementController(userManagementService);
        MockMvc mockMvc = standaloneSetup(apiUserManagementController).build();

        // The actual test     
        mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
    }
}

userManagementServicenullであるために失敗し、自動配線されません。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration       // should default to ApiTests-context.xml in same package
public class ApiTests {

    @Autowired
    UserManagementService userManagementService;

    private MockMvc mockMvc;

    @Before
    public void setup(){
        // SetUp never gets called?!
    }

    @Test
    public void testGetUserById() throws Exception {

        // !!! at this point, userManagementService is still null - why? !!!       

        ApiUserManagementController apiUserManagementController 
            = new ApiUserManagementController(userManagementService);

        mockMvc = standaloneSetup(apiUserManagementController).build();

        // The actual test
        mockMvc.perform(get("/api/user/0").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
    }
}

上記の両方のテストクラスは同じコンテキスト構成を使用する必要があり、userManagementServiceがそこで定義されていることに注意してください。

ApiTests-context.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="user"/>
        <property name="password" value="passwd"/>
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
          p:dataSource-ref="dataSource" p:mappingResources="company.hbm.xml">
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
            </props>
        </property>
        <property name="eventListeners">
            <map>
                <entry key="merge">
                    <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
                </entry>
            </map>
        </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>

    <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

    <context:annotation-config/>
    <tx:annotation-driven/>
    <context:mbean-export/>

    <!-- tried both this and context:component-scan -->
    <!--<bean id="userManagementService" class="com.company.web.hibernate.UserManagementServiceImpl"/>-->
    <context:component-scan base-package="com.company"/>

    <!-- Hibernate's JMX statistics service -->
    <bean name="application:type=HibernateStatistics" class="org.hibernate.jmx.StatisticsService" autowire="byName"/>

</beans>

UserManagementService(インターフェイス)とUserManagementServiceImplには@Serviceアノテーションがあります。

2つの小さな質問/観察:@Beforeアノテーションが付いていても、setup()は呼び出されません。さらに、「test」という名前で始まらない場合、テストメソッドが実行/認識されないことに気付きました。これは、私が見たすべてのspring-mvc-testサンプルでは当てはまりません。

pom.xml:

    <dependency>
        <groupId>org.junit</groupId>
        <artifactId>com.springsource.org.junit</artifactId>
        <version>4.10.0</version>
        <scope>test</scope>
    </dependency>

ここに画像の説明を入力してください

アップデート:

この問題は、Mavenからテストを実行した場合にのみ発生します。IDE(IntelliJ IDEA)内からテストを実行しても問題ありません。

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.3</version>
            <configuration>
                <includes>
                    <include>**/*Tests.java</include>
                </includes>
            </configuration>
        </plugin>
4

3 に答える 3

6

コンポーネントスキャンを実行しない限り、自動配線は行われません。

なぜあなたはそれをあなたのコードでコメントアウトしたのですか?

<!--<context:component-scan base-package="com.company"/>-->

また、re:junit。Eclipseを使用している場合は、pomの依存関係ツリービューに移動して、junitでフィルター処理できます。実際にそのバージョンを使用していて、古いjunitをプルしていないことを確認してください。

編集:わかりました。設定を確認したところ、こちら側で機能させることができました。私の唯一の推測は、あなたがどういうわけか悪いテストランナーでそれを実行しているということです。それはそれが間違ったjunitを使用する原因になっています。

編集2(解決済み):問題は、カスタムバージョンのjunitを使用していることが原因であることがわかりました。Surefireは提供されたjunitライブラリを探し、それを見つけることができません。その結果、デフォルトでjunit 3になります。これにより、アプリは構成の読み込みをスキップします。

次のようなカスタムプロバイダーを明示的に指定できます

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.3</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>2.12.3</version>
      </dependency>
    </dependencies>
  </plugin>

しかし、カスタムリポジトリではうまく機能しないことがわかりました。可能であれば、junitの標準バージョンを使用することをお勧めします。

于 2012-09-21T12:46:54.477 に答える
1

特定のコンテキスト構成を試してください。

@ContextConfiguration(locations = {"/file1.xml", "/file2.xml" })

(必要に応じてこれを複数のファイルで使用する方法を示すだけです。1つで十分な場合があります)

編集:ここで説明したように、AutowiredAnnotationBeanPostProcessorを有効にしましたか?http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

于 2012-09-21T11:37:43.790 に答える
0

私はこれと同じ問題を抱えていました。@AutowireはIDE(SpringSource STS)内で機能しますが、Mavenを使用してコマンドラインからビルドするときにアプリケーションコンテキストをロードできませんでした。

問題は、pom.xmlの依存関係にありました。エラーの原因となったSpringバージョンのJUnitを使用していました。これが元の投稿の根本的な原因だと思います。Mavenプラグインをコーディングする必要はありませんでした。

私が変更され

<dependency>
    <groupId>org.junit</groupId>
    <artifactId>com.springsource.org.junit</artifactId>
    <version>4.7.0</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
</dependency>
于 2013-03-12T20:37:38.857 に答える