如何在Spring XML中定义带有默认答案的Mock

huangapple go评论143阅读模式
英文:

How to define Mock with default Answer in Spring XML

问题

我正在尝试在Spring中使用深度存根定义模拟bean

<bean id="mockLoader" class="org.mockito.Mockito" factory-method="mock">
     <constructor-arg name="classToMock" value="com.foo.Loader" />
     <constructor-arg name="defaultAnswer" type="org.mockito.Answers" value="RETURNS_DEEP_STUBS" />
</bean>

程序出错了

找不到匹配的工厂方法:工厂方法'mock(String,Answers)'。请检查是否存在具有指定名称和参数的方法,且该方法是静态的。

但是静态方法确实存在

https://www.javadoc.io/doc/org.mockito/mockito-all/1.9.5/org/mockito/Mockito.html

public static <T> T mock(java.lang.Class<T> classToMock,
                 Answer defaultAnswer)

我漏掉了什么?还有其他创建带有深度存根的模拟的方法吗?

Mockito版本是1.9.5

Spring版本是4.0.7

谢谢!

英文:

I'm trying to define mock bean in Spring with deep stubs

&lt;bean id=&quot;mockLoader&quot; class=&quot;org.mockito.Mockito&quot; factory-method=&quot;mock&quot; &gt;
     &lt;constructor-arg name=&quot;classToMock&quot; value=&quot;com.foo.Loader&quot; /&gt;
     &lt;constructor-arg name=&quot;defaultAnswer&quot; type=&quot;org.mockito.Answers&quot; value=&quot;RETURNS_DEEP_STUBS&quot; /&gt;
&lt;/bean&gt;

the program is failing with error

> No matching factory method found: factory method 'mock(String,Answers)'. Check that a method with the specified name and arguments exists and that it is static.

but the static method does exist

https://www.javadoc.io/doc/org.mockito/mockito-all/1.9.5/org/mockito/Mockito.html

public static &lt;T&gt; T mock(java.lang.Class&lt;T&gt; classToMock,
                     Answer defaultAnswer)

What am I missing? is there another approach to create mock with deep stubs?

mockito version is 1.9.5

spring version is 4.0.7

thanks!

答案1

得分: 1

使用Mockito的静态字段可能有效

<bean id="mockLoader" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg name="classToMock" value="com.foo.Loader" />
    <constructor-arg name="defaultAnswer">
        <util:constant static-field="org.mockito.Mockito.RETURNS_DEEP_STUBS"/>
    </constructor-arg>
</bean>

你可能需要添加XML命名空间xmlns:util="http://www.springframework.org/schema/util"

英文:

Using the static field of Mockito could work

&lt;bean id=&quot;mockLoader&quot; class=&quot;org.mockito.Mockito&quot; factory-method=&quot;mock&quot; &gt;
     &lt;constructor-arg name=&quot;classToMock&quot; value=&quot;com.foo.Loader&quot; /&gt;
     &lt;constructor-arg name=&quot;defaultAnswer&quot;&gt;
           &lt;util:constant static-field=&quot;org.mockito.Mockito.RETURNS_DEEP_STUBS&quot;/&gt;
     &lt;/constructor-arg&gt;
&lt;/bean&gt;

You might need to add the xml namespace xmlns:util=&quot;http://www.springframework.org/schema/util&quot;

huangapple
  • 本文由 发表于 2020年8月19日 05:12:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63476699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定