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 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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With