Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.UnsupportedOperationException when mocking java.nio.ByteBuffer class

I am trying to mock ByteBuffer class in java.nio with Mockito for testing in JUnit. I get a java.lang.UnsupportedOperationException

My code looks like -

class TestClass {

    @Mock
    private ByteBuffer byteBuffer

     @Before
     public void setup() {
         Mockito.when(byteBuffer.array()).thenReturn("some-string".getBytes()); //this line throws java.lang.UnsupportedOperationException
     }
}

How differently should I mock the array method for this to work? I am using Java 8.

like image 869
krackoder Avatar asked Nov 01 '17 01:11

krackoder


2 Answers

Like in the comment from Sotirios Delimanolis you don't need to mock this class or classes that are easily composed from primitives like byte [].

There are a number of different test doubles (fakes, spies etc.) apart from mocks and this is a better case for a fake than a mock.

Just use:

byteBuffer = ByteBuffer.wrap("some-string".getBytes());
like image 94
David Rawson Avatar answered Nov 09 '22 06:11

David Rawson


You get a java.lang.UnsupportedOperationException because ByteBuffer.array() is a final method. Therefore it is not mocked by Mockito. This means that

Mockito.when(byteBuffer.array()).thenReturn("some-string".getBytes());

calls the real method which throws the exception.

like image 31
Stefan Birkner Avatar answered Nov 09 '22 04:11

Stefan Birkner