java单元测试mock一个静态函数

mockito貌似不支持对静态函数对mock,所以引进“powermock"

1:maven配置


    org.mockito
    mockito-core
    1.10.19
    test


    org.powermock
    powermock-api-mockito
    1.6.5
    test


    org.powermock
    powermock-module-junit4
    1.6.5
    test

2:静态函数伪代码

public class HttpUtils {
public static String doXMLPostSpecifyEncode(String url, String xmlStr, String contentEncodeStr) throws Exception {
   return "bababa";
}

}

 

public class Httpclient {

public String call(String url, String xmlStr)

{

return HttpUtils.doXMLPostSpecifyEncode(url,xmlStr,"utf-8");

}

}

 

 

3:单元测试

@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpUtils.class})
@PowerMockIgnore("javax.management.*")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class STest

{

@Test
public void test03Notice() throws Exception {
    String url = "*****.com/api/xxxx"
    PowerMockito.mockStatic(HttpUtils.class);
    PowerMockito.
            when(HttpUtils.doXMLPostSpecifyEncode(Matchers.eq(url), anyString(), anyString())).thenReturn("cccc");

    new Httpclient().call(url, "mockdata");
}

}

 

ps:标红加粗的参数,不能直接传入url,需要做一个matchers.eq("")

你可能感兴趣的:(java单元测试mock一个静态函数)