Search code examples
javamockingmockitopowermockito

Mockito and PowerMock for ObjectInputStream


I am trying to test a method that uses ObjectInputStream for reading in data from file but I want to use mocks for ObjectInputStream. This method to be tested instantiates a new ObjectInputStream every time it is called, so I need to use PowerMock for mocking the constructor so that everytime an ObjectInputStream is instantiated, it will be a mock. Here is what I have so far:

@Test
public void test() throws Exception {
    ObjectInputStream inputStream = mock(ObjectInputStream.class);
    when(inputStream.readObject()).thenReturn(object);
    PowerMockito.whenNew(ObjectInputStream.class).withAnyArguments().thenReturn(inputStream);
    myFun() // call method to be tested   
}

However, this doesn't work for some reason as I get NullPointerException at when(inputStream.readObject()), which I don't know why. Any ideas on how to mock ObjectInputStream?


Solution

  • @Test
        public void test() throws Exception {
            Object object = mock(Object.class);
            ObjectInputStream inputStream = mock(ObjectInputStream.class);
            when(inputStream.readObject()).thenReturn(object);
            PowerMockito.whenNew(ObjectInputStream.class).withAnyArguments().thenReturn(inputStream);
            myFun() // call method to be tested   
        }
    

    Did you create the object somewhere else?

    And your test should assert against something?