Jmockit:无法模拟 net.android.Uri class 的方法 toString

Jmockit: Can't mock method toString of net.android.Uri class

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

我尝试模拟 class net.android.Uri 的 toString() 方法。此 class 上的所有方法都可以模拟 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() returns 空值,上面的所有方法都被模拟了。 你能给我一些解决方法来解决这个问题吗?

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

Reports any calls to specific methods where the result of that call is ignored. Both methods specified in the inspection's settings and methods annotated with org.jetbrains.annotations.Contract(pure=true) are checked. For many methods, ignoring the result is perfectly legitimate, but for some methods it is almost certainly an error. Examples of methods where ignoring the result of a call is likely to be an error include java.io.inputStream.read(), which returns the number of bytes actually read, any method on java.lang.String or java.math.BigInteger, as all of those methods are side-effect free and thus pointless if ignored.

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

开发者的回答:

Yes, only implemented (with a body, not abstract) toString() methods can be mocked.

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