From 663d1831daa310ddb355cd2aec41c7e56e70cfda Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Fri, 22 Mar 2024 20:15:31 +0200 Subject: [PATCH] This commit is related to BAEL-6404 (#16201) This commit aims to add a test class "UTF8ToISOUnitTest.java" To convert UTF-8 to ISO-8859-1 in Java. --- .../baeldung/UTF8ToISO/UTF8ToISOUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/UTF8ToISO/UTF8ToISOUnitTest.java diff --git a/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/UTF8ToISO/UTF8ToISOUnitTest.java b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/UTF8ToISO/UTF8ToISOUnitTest.java new file mode 100644 index 0000000000..f47ea5fdaf --- /dev/null +++ b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/UTF8ToISO/UTF8ToISOUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.UTF8ToISO; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertArrayEquals; + +public class UTF8ToISOUnitTest { + String string = "âabcd"; + byte[] expectedBytes = new byte[]{(byte) 0xE2, 0x61, 0x62, 0x63, 0x64}; + + @Test + public void givenUtf8String_whenUsingGetByte_thenIsoBytesShouldBeEqual() { + byte[] iso88591bytes = string.getBytes(StandardCharsets.ISO_8859_1); + assertArrayEquals(expectedBytes, iso88591bytes); + } + + @Test + public void givenString_whenUsingByteBufferCharBufferConvertToIso_thenBytesShouldBeEqual() { + ByteBuffer inputBuffer = ByteBuffer.wrap(string.getBytes(StandardCharsets.UTF_8)); + CharBuffer data = StandardCharsets.UTF_8.decode(inputBuffer); + ByteBuffer outputBuffer = StandardCharsets.ISO_8859_1.encode(data); + byte[] outputData = new byte[outputBuffer.remaining()]; + outputBuffer.get(outputData); + assertArrayEquals(expectedBytes, outputData); + } +}