2016-08-25 6 views
0

スプリング注入法による注入法をメソッド注入法でモックする方法はありますか?モーキングスプリングIOC法注入法

私はそれ

public abstract class Singleton { 

    protected abstract LoanField check(); 

    private LoanField getLoanField(String name) { 

    LoanField field = check(); 

} 

で抽象メソッドを持つシングルトンと呼ばれる抽象クラスを持っており、それがコンフィギュレーションに対応しています、私は詳細に

を説明しましょう春-configファイルの一つであります。ここで

<bean id="checkDetails" class="com.abc.tools.Singleton"> 
     <lookup-method name="check" bean="field"/> 
    </bean> 

    <bean id="field" class="com.abc.tools.LoanField" scope="prototype"/> 

私のテストクラスは、ここでは実際の問題は、メソッドに注入春は抽象クラスの与えられた抽象メソッドをオーバーライドし、オーバーライドされたメソッドの実装を提供しますが、ときに私、ある

短い

Singleton fieldManager = Mockito.mock(Singleton.class, Mockito.CALLS_REAL_METHODS); 
LoanField loanField = PowerMockito.mock(LoanField.class); 
PowerMockito.when(fieldManager.create()).thenReturn(loanField); 
であります私は抽象メソッドをスタブにし、そのことはできませんを知っているが、目をスタブに周りのすべての作業があり、私はエラー

java.lang.AbstractMethodError: com.abc.tools.Singleton.create()Lcom/abc/tools/LoanField; 
at com.abc.tools.SingletonTest.loanFiledNotNull(SingletonTest.java:141) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:601) 
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66) 
at 

の下に取得しています私のテストクラスでそのメソッドをスタブにしてみてくださいeメソッド?私を助けてください。

シモンズ:私は、あなたのabstravctクラスを拡張するダミークラスを作るダミー実装を追加し、このクラスをテスト@preparefortest

+0

は、テストコードを表示 –

+0

@Nirレヴィ追加テストクラスのコードスニペット –

答えて

0

内のすべての依存元クラスを述べました。

0

オブジェクトがメソッド注射を介して作成されている場合は、最善のアプローチは、我々はテストケース@contextconfigurationを実行する瞬間はのためのオブジェクトを作成し、テストコードの上にコードスニペットの下に使用され

Singleton s = new Singleton(){ 

    private LoanField getLoanField(String name) { 

     LoanField field = check(); 

    } 

    protected LoanField check(){ 
     return new LoanField(); 
    } 

    } 

    Singleton fieldManager = spy(s); 
    LoanField loanField = mock(LoanField.class); 
    when(fieldManager.create()).thenReturn(loanField); 
+0

http://stackoverflow.com/questions/1087339/using-mockito-to-test-abstract-classes –

0

、スパイで試してみてください抽象クラスを保持し、抽象メソッドも保持します。

@RunWith(MockitoJUnitRunner.class) 
@PrepareForTest({LoggerFactory.class,Class.class}) 
@ContextConfiguration("file:src/test/resources/META-INF/spring-config-test.xml") 
public class TestClass { 

基本的に、実際のxmlファイルと同じtest xmlファイルを用意し、@contextConfigurationを使用してロードする必要があります。

ありがとうございました。

関連する問題