From 82ca2b8b92f811ade05f0f10817ea0ab53a8d6cd Mon Sep 17 00:00:00 2001 From: danielmcnally285 <144589379+danielmcnally285@users.noreply.github.com> Date: Sat, 16 Mar 2024 12:23:28 +0000 Subject: [PATCH] last n characters from string unit tests --- .../LastNCharactersUnitTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/lastncharacters/LastNCharactersUnitTest.java diff --git a/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/lastncharacters/LastNCharactersUnitTest.java b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/lastncharacters/LastNCharactersUnitTest.java new file mode 100644 index 0000000000..1dd45b0d89 --- /dev/null +++ b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/lastncharacters/LastNCharactersUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.lastncharacters; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class LastNCharactersUnitTest { + + private String s; + private int n; + + @Test + void givenString_whenUsingIntStreamAsStreamSource_thenObtainLastNCharacters() { + String result = s.chars() + .mapToObj(c -> (char) c) + .skip(s.length() - n) + .map(String::valueOf) + .collect(Collectors.joining()); + assertThat(result).isEqualTo("2024"); + } + + @Test + void givenString_whenUsingOneArgSubstringMethod_thenObtainLastNCharacters() { + int beginIndex = s.length() - n; + assertThat(s.substring(beginIndex)).isEqualTo("2024"); + } + + @Test + void givenString_whenUsingStreamOfCharactersAsSource_thenObtainLastNCharacters() { + String result = Arrays.stream(ArrayUtils.toObject(s.toCharArray())) + .skip(s.length() - n) + .map(String::valueOf) + .collect(Collectors.joining()); + assertThat(result).isEqualTo("2024"); + } + + @Test + void givenString_whenUsingStringUtilsRight_thenObtainLastNCharacters() { + assertThat(StringUtils.right(s, n)).isEqualTo("2024"); + } + + @Test + void givenString_whenUsingTwoArgSubstringMethod_thenObtainLastNCharacters() { + int beginIndex = s.length() - n; + String result = s.substring(beginIndex, s.length()); + assertThat(result).isEqualTo("2024"); + } + + @BeforeEach + void init() { + s = "10-03-2024"; + n = 4; + } +} \ No newline at end of file