java - 带参数的模拟方法

标签 java mockito

我试图模拟下面的行,但它在执行时出错,它说:

Misplaced argument matcher detected here:

You cannot use argument matchers outside of verification or stubbing.

Examples of correct usage of argument matchers:

when(mock.get(anyInt())).thenReturn(null);

doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());

verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods cannot be stubbed/verified: final/private/equals()/hashCode().

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: The line of code is:

PowerMockito.mockStatic(NameOfClass.class);
expect( NameOfClass.nameOfMethod((URL)Mockito.any(),Mockito.anyString())).andReturn(actualOutput);

这个类有点像这样:

public class SomeClass {
    public static String method(String URL, String str) {
    //functioning
        return "";
    }
}

我如何模拟它?

最佳答案

您可以在 Mockito 之上使用 PowerMockito。像这样的事情:

PowerMockito.mockStatic(NameOfClass.class);
expect( NameOfClass.nameOfMethod((URL)Mockito.any(),Mockito.anyString())).andReturn(actualOutput);

关于java - 带参数的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062928/

相关文章:

java - 有什么方法可以轻松地在 Java Applet 中显示非常大的图像(使用较少的部分)?

java - 避免 java lambda 中不需要的返回值

java - 插入数据库的集成测试问题

java - Mockito Junit 测试 - “Wanted but not invoked; However there were other interactions with this mock” 错误

java - 如何使用 java.util.Date 进行日历算术?

java - ANTLR - 嵌入 Java 代码,评估之前还是之后?

java - 消息驱动的 Bean 选择器 (JMS)

EasyMock 与 Mockito : design vs maintainability?

java - 为什么不能同时使用 Mock 和 InjectMocks?

java - Spring Boot - MockMVC 创建 bean 时出错