我有一个如下所示的函数。
public String getDecodedToken() throws UnsupportedEncodingException {
if (token == null) {
String token = ClassContainingStatic
.findString("static");
this.token = new String(Base64.decodeBase64(token), "UTF-8");
}
return token;
}
为了测试该函数,我不想模拟 ClassContainingStatic 类,因为它会使测试变得无用。相反,我想看看调用是否发生在 ClassContainingStatic.findString("static") 上而不模拟该对象。有没有办法实现对真实对象的函数调用次数?
最佳答案
通过一些重构当然是可能的。如果您在单独的方法中提取对静态类的调用:
public String getDecodedToken() throws UnsupportedEncodingException{
if( token == null ){
token = createToken();
}
return token;
}
String createToken() throws UnsupportedEncodingException{
String token = ClassContainingStatic.findString("static");
return new String( Base64.decodeBase64(token), "UTF-8" );
}
现在您可以创建一个模拟或 spy ,并简单地验证该方法是否被调用。
ClassUnderTest spy = Mockito.spy( new ClassUnderTest() );
String token = spy.getDecodedToken();
Mockito.verify( spy ).createToken();
我假设“static”
字符串是固定的。如果没有,请将其作为参数传递给createToken
类,然后您可以相应地调整verify
。
我可能在 Mockito 语法中犯了一个错误,但总体思路应该很清楚。唯一的缺点是您需要创建一个包可见/ protected (如果您愿意,甚至可以公开,但通常情况并非如此)方法,以便可以进行 verify
调用。
关于java - 如何查找静态函数被调用 Mockito 的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26442567/