如何使用mockito为静态方法类编写junit



如何在JUnit中模拟和期望以下代码?

esGateKeeper.esGateKeeper(Mockito.anyString(), "Somethin", "Something")

我的完整示例类:

import esGateKeeper.esGateKeeper;//external library
Class Common {
public static String getUserId(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
String test = null;
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
String cookieName = thisCookie.getName();
if ("test".equals(cookieName)) {
test = thisCookie.getValue();
break;
}
}
String encrypted = esGateKeeper.esGateKeeper(test, "CSP", "PROD");///unable to mock this in mockito framework
String userId = encrypted.split("\|")[5];
return userId;
}
}

直到循环在做junit时工作。在那之后,我再也不能嘲笑这种说法了。

您可以将PowerMockito与JUnit结合使用,这里有一个示例

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassWithStaticMethod.class})
public class SomeStaticMethodTest {
@Test
public void testSomething() {
PowerMockito.mockStatic(ClassWithStaticMethod.class);
when(ClassWithStaticMethod.getInstance()).thenReturn(new MockClassWithStaticMethod()); // getInstance() is a static method
//some test condition
}    
}

更多信息请点击此处。

干杯!

最新更新