From 67c9b1e86f5fff5fe03f04e44135a8018bd813d6 Mon Sep 17 00:00:00 2001 From: Holger Date: Wed, 29 Nov 2017 22:37:54 +0000 Subject: [PATCH] BAEL-1376: Varargs Code Example (#3129) * BAEL-1376: Varargs Code Example * BAEL-1376: Varargs Code Example Moving the "logic" into a test and removing the unnecessary class. --- .../com/baeldung/varargs/FormatterTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/varargs/FormatterTest.java diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java new file mode 100644 index 0000000000..509c8764d2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java @@ -0,0 +1,60 @@ +package com.baeldung.varargs; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class FormatterTest { + + private final static String FORMAT = "%s %s %s"; + + @Test + public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() { + String actualResult = format(); + + assertThat(actualResult, is("empty ")); + } + + @Test + public void givenOneArgument_thenResultHasTwoTrailingSpace() { + String actualResult = format("baeldung"); + + assertThat(actualResult, is("baeldung ")); + } + + @Test + public void givenTwoArguments_thenOneTrailingSpaceExists() { + String actualResult = format("baeldung", "rocks"); + + assertThat(actualResult, is("baeldung rocks ")); + } + + @Test + public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() { + String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring"); + + assertThat(actualResult, is("baeldung rocks java")); + } + + public String format() { + return format("empty", ""); + } + + public String format(String value) { + return format(value, ""); + } + + public String format(String val1, String val2) { + return String.format(FORMAT, val1, val2, ""); + } + + public String formatWithVarArgs(String... values) { + if (values.length == 0) { + return "no arguments given"; + } + + return String.format(FORMAT, values); + } + +} \ No newline at end of file