模拟弹簧IOC方法注入的方法

时间:2016-08-25 11:49:19

标签: java mockito powermockito

有没有办法模拟弹簧容器使用方法注入方法注入的方法。

让我详细解释一下

我有一个名为Singleton的抽象类,其中包含抽象方法

public abstract class Singleton {

    protected abstract LoanField check();

    private LoanField getLoanField(String name) {

    LoanField field = check();

}

并且其中一个spring-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);

这里的实际问题是,在方法注入Spring中,重写抽象类的给定抽象方法,并提供重写方法的实现,但是当我尝试在我的测试类中存根该方法时,我得到以下错误

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 

我知道它不可能存根抽象方法但是有任何解决方法存根吗?请帮帮我。

Ps:我在@preparefortest

中提到了所有依赖的课程

3 个答案:

答案 0 :(得分:0)

创建扩展abstravct类的虚拟类,添加虚拟实现并测试此类。

答案 1 :(得分:0)

尝试使用间谍,

    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);

答案 2 :(得分:0)

如果通过方法注入创建对象,那么最好的方法是在测试代码之上的代码片段下面使用,我们运行测试用例@contextconfiguration的那一刻将为抽象类创建对象,你也将掌握抽象方法

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

基本上你应该有一个与实际xml文件相同的测试xml文件,并使用@contextConfiguration加载它。

感谢。