我正在使用来自apache commons lang3库的RandomStringUtils类。我在嘲笑它的随机方法时遇到了问题。
下面是我的示例类,它带有简单的方法generatePassword。
public class Example() {
public String generatePassword() {
final String randomDevicePass = RandomStringUtils.random(10, "abcdefghijklmnopqrstuvwxyz");
System.out.println(randomDevicePass)
return randomDevicePass;
}
}
下面是我的测试类,通过它我正在运行测试用例。
@RunWith(MockitoJUnitRunner.class)
public class ExampleTest() {
@InjectMocks
private Example Example;
@Mock
RandomStringutils randomStringutils;
@Test
public void givenCharacters_returnStringPassword() {
Mockito.when(randomStringUtils.random(Mockito.anyInt(),Mockito.anyString())).thenReturn("asdf");
Assertions.assertEquals("asdf", example.generatePassword());
}
}
它给出以下错误:
Misplaced or misused 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"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
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().
Mocking methods declared on non-public parent classes is not supported.
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
我不知道如何模仿Java内置的apache公共库类。不知道我们能不能用spy?或者别的什么...有人能帮我这个忙吗?
先谢了
1条答案
按热度按时间hc8w905p1#
每当你需要模仿一个静态方法时,这通常有点代码味道,但是,在Mockito库中有一些方法可以做到这一点。
首先,将一个文件添加到测试资源目录的新文件夹
mockito-extensions
中,文件名应为org.mockito.plugins.MockMaker
,该文件需要包含一行:模型制造者联机然后您就可以通过Mockito.mockStatic添加一个静态mock了,如下所示: