From e37e3abf5176102762014008ba16a8abe58db154 Mon Sep 17 00:00:00 2001 From: Thach Le Date: Wed, 3 Jul 2024 14:59:59 +0700 Subject: [PATCH] Handle NPE (#2906) * Handle NPE * Add Unit Test --- .../io/lettuce/core/codec/ByteArrayCodec.java | 4 ++- .../core/codec/ByteArrayCodecUnitTests.java | 35 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java diff --git a/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java b/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java index c8a9cffd06..bcecd3d283 100644 --- a/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java +++ b/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java @@ -90,9 +90,11 @@ public ByteBuffer encodeValue(byte[] value) { } private static byte[] getBytes(ByteBuffer buffer) { + if (buffer == null) { + return EMPTY; + } int remaining = buffer.remaining(); - if (remaining == 0) { return EMPTY; } diff --git a/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java b/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java new file mode 100644 index 0000000000..c8f2394dac --- /dev/null +++ b/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java @@ -0,0 +1,35 @@ +package io.lettuce.core.codec; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; + +import static org.assertj.core.api.Assertions.assertThat; + +class ByteArrayCodecUnitTests { + + @Test + void testDecodeValue_withNonEmptyByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final byte[] expectedBytes = { 1, 2, 3, 4, 5 }; + final ByteBuffer buffer = ByteBuffer.wrap(expectedBytes); + final byte[] result = byteArrayCodec.decodeValue(buffer); + assertThat(result).isEqualTo(expectedBytes); + } + + @Test + void testDecodeValue_withEmptyByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final ByteBuffer buffer = ByteBuffer.allocate(0); + final byte[] result = byteArrayCodec.decodeValue(buffer); + assertThat(result).isEmpty(); + } + + @Test + void testDecodeValue_withNullByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final byte[] result = byteArrayCodec.decodeValue(null); + assertThat(result).isEmpty(); + } + +}