【问题标题】:Jmockit: Can't mock method toString of net.android.Uri classJmockit:无法模拟 net.android.Uri 类的方法 toString
【发布时间】:2017-05-24 12:01:38
【问题描述】:

IDE:Android Studio 2.2.2 | Jmockit:2.1 | Java:1.8.0_102-b14

我试图模拟 net.android.Uri 类的 toString() 方法。这个类的所有方法都可以 mock OK,但是 toString() 方法。

@Test
public void method(@Mocked final Uri uri) throws Exception {
    new NonStrictExpectations() {
            {
                uri.getHost();
                result = "sendViewLog";
                uri.getAuthority();
                result = "getAuthority";
                uri.getEncodedFragment();
                result = "getEncodedFragment";
                uri.getPort();
                result = 8080;
                uri.toString(); // <-------
                result = "helloWorld";
            }
        };      

    sut.method();
}

结果: 但是 toString() 返回 null 值,上面的所有方法都被模拟了。 你能给我一些解决这个问题的方法吗?

PS1: 我意识到,当我将鼠标悬停在 Expectations 块内的 toString 方法上时。它显示以下警告消息:

报告对特定方法的任何调用,该调用的结果是 忽略。检查设置中指定的两种方法和 用 org.jetbrains.annotations.Contract(pure=true) 注释的方法 被检查。对于许多方法,忽略结果是完美的 合法的,但对于某些方法,它几乎可以肯定是一个错误。 可能会忽略调用结果的方法示例 是一个错误包括 java.io.inputStream.read(),它返回 实际读取的字节数,java.lang.String 上的任何方法或 java.math.BigInteger,因为所有这些方法都没有副作用,并且 如果忽略则毫无意义。

PS2: 当我通过 uri 实例检查 null 时,它通过了。 但是,我要检查的客户端代码是 uri.toString().contains("/video") 原因 uri.toString() == null,所以 contains("/video") 抛出 NullPointerException。

【问题讨论】:

    标签: java android junit jmockit


    【解决方案1】:

    开发者的回答:

    是的,只有实现(带有主体,而不是抽象)toString() 方法可以被模拟。

    https://github.com/jmockit/jmockit1/issues/381

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 2014-08-17
      相关资源
      最近更新 更多