|
| 1 | +package com.baeldung.bytebuffer; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertArrayEquals; |
| 4 | + |
| 5 | +import java.nio.ByteBuffer; |
| 6 | + |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | + |
| 9 | +class ByteBufferToByteArrayConversionUnitTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + void whenUsingArrayMethod_thenConvertToByteArray() { |
| 13 | + byte[] givenBytes = {1, 6, 3}; |
| 14 | + ByteBuffer buffer = ByteBuffer.wrap(givenBytes); |
| 15 | + byte[] bytes = buffer.array(); |
| 16 | + |
| 17 | + assertArrayEquals(bytes, givenBytes); |
| 18 | + } |
| 19 | + |
| 20 | + @Test |
| 21 | + void whenUsingGetMethod_thenConvertToByteArray() { |
| 22 | + byte[] givenBytes = {5, 4, 2}; |
| 23 | + ByteBuffer buffer = ByteBuffer.wrap(givenBytes); |
| 24 | + byte[] bytes = new byte[buffer.remaining()]; |
| 25 | + buffer.get(bytes); |
| 26 | + |
| 27 | + assertArrayEquals(bytes, givenBytes); |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + void whenUsingWrapMethod_thenConvertToByteBuffer() { |
| 32 | + byte[] givenBytes = {1, 2, 3}; |
| 33 | + ByteBuffer buffer = ByteBuffer.wrap(givenBytes); |
| 34 | + |
| 35 | + assertArrayEquals(buffer.array(), givenBytes); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + void whenUsingAllocateAndPutMethods_thenConvertToByteBuffer() { |
| 40 | + byte[] givenBytes = {1, 9, 7}; |
| 41 | + ByteBuffer buffer = ByteBuffer.allocate(givenBytes.length); |
| 42 | + buffer.put(givenBytes); |
| 43 | + |
| 44 | + assertArrayEquals(buffer.array(), givenBytes); |
| 45 | + } |
| 46 | +} |
0 commit comments