[英]Mock a static method used inside a private method without using powermock
我想模擬在 class 的私有方法中使用的 static 方法並返回特定值。
public class Test {
private String encodeValue(String abc) {
try {
return URLEncoder.encode(...);
} catch (UnsupportedEncodingException e) {
throw InvalidValueException.create("Error converting");
}
}
URLEncoder.encode ->encode 是 URLEncoder 中的 static 方法。
在測試 class 使用 powermock 作品:
PowerMock.mockStatic(URLEncoder.class);
expect(URLEncoder.encode()).andThrow(new UnsupportedEncodingException());
PowerMock.replay(URLEncoder.class);
String encoded = Whitebox.invokeMethod(testMock,"encodeVaue","Apple Mango");
但我想用任何其他可用的 mocking 方式替換 Powermock。 有沒有辦法模擬上面的 class。
URL 編碼器 class:
/**
* Translates a string into {@code application/x-www-form-urlencoded}
* format using a specific encoding scheme. This method uses the
* supplied encoding scheme to obtain the bytes for unsafe
* characters.
* <p>
* <em><strong>Note:</strong> The <a href=
* "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
* World Wide Web Consortium Recommendation</a> states that
* UTF-8 should be used. Not doing so may introduce
* incompatibilities.</em>
*
* @param s {@code String} to be translated.
* @param enc The name of a supported
* <a href="../lang/package-summary.html#charenc">character
* encoding</a>.
* @return the translated {@code String}.
* @exception UnsupportedEncodingException
* If the named encoding is not supported
* @see URLDecoder#decode(java.lang.String, java.lang.String)
* @since 1.4
*/
public static String encode(String s, String enc)
throws UnsupportedEncodingException {
boolean needToChange = false;
StringBuffer out = new StringBuffer(s.length());
Charset charset;
CharArrayWriter charArrayWriter = new CharArrayWriter();
if (enc == null)
throw new NullPointerException("charsetName");
try {
charset = Charset.forName(enc);
} catch (IllegalCharsetNameException e) {
throw new UnsupportedEncodingException(enc);
} catch (UnsupportedCharsetException e) {
throw new UnsupportedEncodingException(enc);
}
for (int i = 0; i < s.length();) {
int c = (int) s.charAt(i);
//System.out.println("Examining character: " + c);
if (dontNeedEncoding.get(c)) {
if (c == ' ') {
c = '+';
needToChange = true;
}
//System.out.println("Storing: " + c);
out.append((char)c);
i++;
} else {
// convert to external encoding before hex conversion
do {
charArrayWriter.write(c);
/*
* If this character represents the start of a Unicode
* surrogate pair, then pass in two characters. It's not
* clear what should be done if a bytes reserved in the
* surrogate pairs range occurs outside of a legal
* surrogate pair. For now, just treat it as if it were
* any other character.
*/
if (c >= 0xD800 && c <= 0xDBFF) {
/*
System.out.println(Integer.toHexString(c)
+ " is high surrogate");
*/
if ( (i+1) < s.length()) {
int d = (int) s.charAt(i+1);
/*
System.out.println("\tExamining "
+ Integer.toHexString(d));
*/
if (d >= 0xDC00 && d <= 0xDFFF) {
/*
System.out.println("\t"
+ Integer.toHexString(d)
+ " is low surrogate");
*/
charArrayWriter.write(d);
i++;
}
}
}
i++;
} while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
charArrayWriter.flush();
String str = new String(charArrayWriter.toCharArray());
byte[] ba = str.getBytes(charset);
for (int j = 0; j < ba.length; j++) {
out.append('%');
char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
// converting to use uppercase letter as part of
// the hex value if ch is a letter.
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
ch = Character.forDigit(ba[j] & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
}
charArrayWriter.reset();
needToChange = true;
}
}
return (needToChange? out.toString() : s);
}
Mocking 私有和靜態是 JMockit 相對於其他 mocking 框架的主要優勢之一。
您稱為“Test”的class實際上是“ClassUnderTest”,所以很抱歉,但是“Test”的測試是“TestTest”:)
public class TestTest {
@Tested
public Test cut;
@Test
public void testencodeValue() {
// Mock the static
new MockUp<URLEncoder>() {
@Mock
String encode(String s, String enc) {
return "JMockit FTW";
}
};
// invoke the private method
final Method method = MethodReflection.findCompatibleMethod(Test.class, "encodeValue", new Class<?>[] { String.class });
final String res = MethodReflection.invoke(cut, method);
assertEquals("JMockit FTW", res);
}
}
也就是說,測試私人是一種 PITA。 我通常認為,如果一種方法值得測試,那么幾乎可以肯定它值得公開。 使該方法值得測試的相同標准意味着某天某個地方的某個人會想要覆蓋您的實現並提供一個稍微替代的實現。 讓他們的工作變得輕松,並使其受到保護。 讓您的(測試)工作變得輕松,並做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.