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

坚强是说给别人听的谎言 提交于 2019-12-23 05:38:10

问题


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

I tried to mock method toString() of class net.android.Uri. All method on this class could mock OK, but toString() method.

@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();
}

Result: But toString() returns null value, all method above were mocked. Could you give me some solution method resolve this problem.

PS1: I realized that when i hover to toString method inside Expectations block. It shows this warning message:

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: When I check null by uri instance, it passes. But, code from client which I want to check is uri.toString().contains("/video") Cause uri.toString() == null, so contains("/video") throws NullPointerException.


回答1:


Answer from developer:

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

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



来源:https://stackoverflow.com/questions/41561351/jmockit-cant-mock-method-tostring-of-net-android-uri-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!