2
public class ConnectionPointTest {

    @Test
    public void testMockito() throws IOException {

        DataInputStream dataInputStream = mock(DataInputStream.class);
        when(dataInputStream.readUTF()).thenReturn("Test");
        new JustTest(dataInputStream).doTest();

    }

    public class JustTest {
        DataInputStream dataInputStream;

        public JustTest(DataInputStream dataInputStream) {
            this.dataInputStream = dataInputStream;
        }

        public void doTest() throws IOException {
            String s = dataInputStream.readUTF();
            System.out.println(s);
        }
    }
}

I implement JUnit testing + Mockito in the project. Then I try to mock my DataInpuStream, I have an exeption at this code :

 when(dataInputStream.readUTF()).thenReturn("Test");

P.S. class JustTest is only for show you what I want to mock.

There is exeption:

java.lang.NullPointerException
    at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:337)
    at java.io.DataInputStream.readUTF(DataInputStream.java:589)
    at java.io.DataInputStream.readUTF(DataInputStream.java:564)
    ...
0

1 Answer 1

4

You are trying to mock a final method:

public final String readUTF() throws IOException {
    return readUTF(this);
}

Mockito (v2.x) supports this but it requires additional configuration. More details in the docs:

Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline

So, create a file named org.mockito.plugins.MockMaker with this content:

mock-maker-inline

Place this file in a folder named mockito-extensions on your test classpath (if you are using Maven just create this folder in src/test/resources)

Re run your test.

With this configuration in place I have successful run your test with:

  • JUnit 4.12
  • Mockito 2.7.19
1
  • Thanks! You just saved a lot of my time!
    – AvdPav
    Commented Aug 24, 2018 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.