【问题标题】:Mock a static method used inside a private method without using powermock在不使用 powermock 的情况下模拟私有方法内部使用的静态方法
【发布时间】:2020-11-13 07:15:32
【问题描述】:

我想模拟一个在类的私有方法中使用的静态方法并返回一个特定的值。

 public class Test {

    private String encodeValue(String abc) {

    try {
        return URLEncoder.encode(...);
    } catch (UnsupportedEncodingException e) {
        throw InvalidValueException.create("Error converting");
    }
}

URLEncoder.encode ->encode 是 URLEncoder 内部的一个静态方法。

在使用 powermock 的测试类中工作:

    PowerMock.mockStatic(URLEncoder.class);
    expect(URLEncoder.encode()).andThrow(new UnsupportedEncodingException());
    PowerMock.replay(URLEncoder.class);
    String encoded = Whitebox.invokeMethod(testMock,"encodeVaue","Apple Mango");

但我想用任何其他可用的模拟方式替换 Powermock。 有没有办法模拟上面的类。

URL 编码器类:

 /**
 * 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);
}

【问题讨论】:

  • 请提供URLEncoder 类的详细信息。什么情况下可能抛出异常?
  • hi @chrylis -cautiouslyoptimistic 此类用作项目中的外部库及其只读文件。我已经更新了上面的类代码。请查看并提供您的宝贵建议

标签: java junit mocking mockito jmockit


【解决方案1】:

模拟私有和静态是 JMockit 相对于其他模拟框架的主要优势之一。

你称之为“Test”的类实际上是“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。我通常认为,如果一种方法值得测试,那么几乎可以肯定它值得公开。使该方法值得测试的相同标准意味着某天某个地方的某个人会想要覆盖您的实现并提供一个稍微替代的实现。让他们的工作变得轻松,并使其受到保护。让您的(测试)工作变得轻松,并做同样的事情。

【讨论】:

  • 感谢您的回复,但在使用 @Mock 时 - 它表示此处不允许使用注释。你能告诉我应该在哪里使用这个注释吗?
  • 也想知道是否有可能抛出特定异常 expect(URLEncoder.encode()).andThrow(new UnsupportedEncodingException()); - 在 JMockit 中就像这样
  • 确保您使用的是最新版本的 JMockit,并确保它确实在使用 @mockit.Mock(我怀疑您是从另一个框架中获取 Mock)。
  • 是的,在上面的 MockUp 中,你当然可以 throw 而不是 return
  • 导入 org.mockito.Mock; testImplementation 'org.jmockit:jmockit:1.48.x' testCompile group: 'org.jmockit', name: 'jmockit', version: '1.48' 我已经使用了这些依赖项并导入了我仍然面临的问题。你能帮忙吗?
猜你喜欢
  • 2017-12-11
  • 2018-10-19
  • 1970-01-01
  • 2013-07-17
  • 2012-03-31
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多