2

Spring JUnit テスター クラスがありMySimpleTesterます。

@

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/spring/mySimpleConfig.xml"})
public class MySimpleTester {

@Before
    public void setUp() throws Exception {
        myAdapter = (MyAdapter) applicationContext.getBean("myAdapter");
    }

@test 
public void testGetSimpleList() {
        List<SimpleLink> simpleList = **myAdapter.getSimpleLinksList**();
}

... ... ...

私が持っているアダプタクラスでは:

public MyAdapter {
    public List<SimpleLink> getSimpleLinksList() {
        List<SimpleLink> simLinks = null;
        String environment = AppFactory.getPropertiesObj();

... ... ...

class AppFactory implements ApplicationContextAware {

    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext acontext) {
        context = acontext;
    }
    public getPropertiesObj() {
        return getAppContext().getBean("propertiesBean");
    }

NullPointerExceptionはそれApplicationContextNullここにあることを理解しています。

ただし、SpringJUnitTestRunnerクラスMySimpleTesterでは、applicationContext が正しく初期化されていることがわかりました。mySimpleConfig.xmlおよび インクルード ファイルは含めません。MyAdapterアプリケーション サーバーで実行すると、クラス内のメソッドgetSimpleLinksList()は Web アプリケーションから完全に正常に動作し、そこで appcontext が取得されます。

AppFactoryを介して静的に呼び出されるため、Spring テスターからのみ、静的アプリケーション コンテキスト クラスに到達できませんAppFactory.getPropertiesObj()。他のテストクラスが実行されているため、クラスパスを正しく設定しました。

4

2 に答える 2

0

複数のアプリケーション コンテキストが作成されると発生していると思います。AplliCationContext オブジェクトはシングルトンであると想定されています。しかし、静的メソッドから再び applicationContext を呼び出すと、まったく異なる構成が参照されます。ApplicationContext はそこで初期化されていません。

これは、同じモジュールが Spring MVC webcontanier から呼び出された場合には発生しません。Spring テスター クラス RunWith(SpringJUnit4ClassRunner.class) を使用しようとした場合にのみ発生します。ビジネス メソッドで AppContext を渡すことはできますが、ビジネス メソッドのシグネチャを変更したくありません。同様の問題を抱えた春のコミュニティでいくつかのスレッドを見つけました。

于 2015-08-24T15:57:16.730 に答える
0

MySimpleTester で現在の ApplicationContext にアクセスする場合:-

public class MySimpleTester {

@Autowired
ApplicationContext applicationContext;

@Before
    public void setUp() throws Exception {
        myAdapter = (MyAdapter) applicationContext.getBean("myAdapter");
    }

@test 
public void testGetSimpleList() {
        List<SimpleLink> simpleList = **myAdapter.getSimpleLinksList**();
}
于 2015-08-22T03:30:09.993 に答える