如何解决在此处检测到错误的参数匹配器您不能在Mockito中的验证或存根之外使用参数匹配器
您anyString()
在调用测试方法时使用了模仿,它仅用于验证模拟对象,以确保使用测试中的任何字符串参数调用某个方法,而不能调用测试本身。为了测试,请使用空字符串""
代替anyString()
。
解决方法
在 BundleProcessorTest.java 的以下两个测试用例中,尽管我的第一个测试用例成功通过,但我低于异常。
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:在此处检测到放错位置的参数匹配器:
->在bundle.test.BundleProcessorTest.bundlePluginShouldNotBeNull(BundleProcessorTest.java:22)
您不能在验证或存根之外使用参数匹配器。正确使用参数匹配器的示例:when(mock.get(anyInt()))。thenReturn(null);
doThrow(new RuntimeException())。when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains(“ foo”))另外,可能会出现此错误,因为您将参数匹配器与无法模拟的方法一起使用。以下方法 不能 存根/验证:final / private /
equals()/ hashCode()。在bundle.test.BundleProcessorTest.bundlePluginCollectionShouldNotBeNull(BundleProcessorTest.java:28)在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)在sun.reflect.NativeMethodAccessorImpl.invoke(未知源)
请在下面找到简化的代码清单:
BundlePlugin.java
package bundle;
import java.util.List;
public class BundlePlugin {
private final String pluginName ;
private final List<String> featureContent ;
public BundlePlugin(String pluginName,List<String> featureContent) {
super();
this.pluginName = pluginName;
this.featureContent = featureContent;
}
public String getPluginName() {
return pluginName;
}
public List<String> getFeatureContent() {
return featureContent;
}
}
BundleProcessor.java
package bundle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BundleProcessor {
public BundlePlugin getBundlePlugin(String pluginName,Iterator<String> artifactIterator) {
List<String> featureContent = new ArrayList<String>() ;
return new BundlePlugin(pluginName,featureContent);
}
}
BundleProcessorTest.java
package bundle.test;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import bundle.BundleProcessor;
public class BundleProcessorTest {
BundleProcessor bundleProcessor = new BundleProcessor() ;
@Test
public void bundlePluginShouldNotBeNull() {
Iterator<String> artifactIterator = mock(Iterator.class) ;
bundle.BundlePlugin bundlePlugin = bundleProcessor.getBundlePlugin(anyString(),artifactIterator) ;
assertNotNull( bundlePlugin );
}
@Test
public void bundlePluginContentShouldNotBeNull() {
Iterator<String> artifactIterator = mock(Iterator.class) ;
bundle.BundlePlugin bundlePlugin = bundleProcessor.getBundlePlugin(anyString(),artifactIterator) ;
List<String> featureContent = bundlePlugin.getFeatureContent() ;
assertNotNull( featureContent );
}
}
如何毫无问题地执行此测试。
编辑1:
但是,如果我使用@Ignore注释将 bundlePluginCollectionShouldNotBeNull
测试标记为测试,则第一个测试用例将毫无例外地通过。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。