Search code examples
javaandroidjunitjmockit

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

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.


Solution

  • Answer from developer:

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

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