假设我正在测试以下方法。
Set
当我测试时,我可以为非空目的进行模拟吗?
/**
* Does something. This method throws a {@code NullPointerException}
* either given string or specified charset is {@code null}.
* @param s the string
* @param c the charset
*/
void doSomething(String s, Charset c) {
}
是否有用于模拟一般非空值的库/方法?
我试过assertThrows(NullPointerException.class,
new MyObject().doSomething(null, UTF_8));
assertThrows(NullPointerException.class,
new MyObject().doSomething("", null));
,似乎为某些无效类型抛出了一个Exception,因为它实际上可以模拟。
更新
通过user2004685的回答,现在,我很好奇我是否可以像这样使用Mockito.mock
或anyString
。
any(Class)
答案 0 :(得分:1)
这是void
方法。如果你使用Mockito来嘲笑它以抛出异常,那么你需要做这样的事情:
Mockito.doThrow(new NullPointerException("Description"))
.when(mymock)
.doSomething(Mockito.anyString(), Mockito.any(Charset.class));
即使将null
传递给方法,它也应该有效。