简体   繁体   中英

mocking UrlEncoder in a static method

I'm having trouble mocking UrlEncode.encode method which is inside a static method.

MyEncodeClass.java has this method

public static myEncode(String s) {
  UrlEncoder.encode(s, "utf-8");
}

I want to force throw an exception when UrlEncode.encode method is called.

@Test(expect = UnsupportedEncodingException.class)
public void myTest() {
    PowerMockito.mockStatic(URLEncoder.class);        
    when(URLEncoder.encode("aa", "utf-8")).thenThrow(UnsupportedEncodingException.class);    
    MyEncodeClass.myEncode("aa");
}

but I always get the following exception

Caused by: java.lang.NoSuchMethodError: org.mockito.mock.MockCreationSettings.isUsingConstructor()Z

it is because of the version conflict between PowerMockito and Mockito artifacts. "MockCreationSettings.isUsingConstructor" method is removed in new versions, so you need to be sure you are using correct versions. eg use PowerMockito version 1.6.2 with Mockito version 1.10.19 (this version has that missing method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM