0

applicationContext の使用方法を学ぼうとしています。私の目標は、単体テストを使用するときに、モック データ リポジトリを実際のデータ リポジトリに交換することです。私はこれを明示的に行いたくありません。依存性注入でこれを行いたいです。

物事を複雑にする前の簡単なテストとして、単純に applicationContext.xml から Bean を取得しようとしています。私が読んだことから、これはうまくいくはずです:

@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {

     @Resource
     CompanyResult resultBean;

     @Test
     public void shouldAddResults() {
         assertEquals(resultBean.getCompanyName(), "Microsoft");

しかし、私のresultBeanは常にnullです。WebContent/WEB-INF の下にある私の applicationContext.xml は次のとおりです。

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="resultBean" name="resultBean" class="com.trgr.cobalt.company.domain.CompanyResult">
        <property name="companyName">
            <value>Microsoft</value>
        </property>
     </bean>
</beans>

では、なぜ私の resultBean は常に null なのですか? 私は間違って何をしましたか?

4

1 に答える 1

1

@RunWith(SpringJUnit4ClassRunner.class)注釈がありません:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {

     @Resource
     CompanyResult resultBean;

     @Test
     public void shouldAddResults() {
         assertEquals(resultBean.getCompanyName(), "Microsoft");
     }
}

ところで、あなたのサンプルでWebContent/WEB-INFは、​​ の適切な場所ではありませんapplicationContext.xml

指定する@ContextConfiguration(locations = "/applicationContext.xml")と、Spring はapplicationContext.xmlクラスパスのルートではなく、ルートを検索しますWebContent/WEB-INF(jUnit は、これが Web アプリケーションであるという事実を 100% 認識しません)。

詳細については、 Spring リファレンス ドキュメントを参照してください。

于 2010-11-17T18:21:15.767 に答える