From d429988e739442261639f22dee77efdad1baae46 Mon Sep 17 00:00:00 2001 From: "Jerry (Xinyu Hou)" Date: Thu, 29 Oct 2015 13:00:03 -0700 Subject: [PATCH] Add more unit tests for split string function #4933 --- src/lib/base/String.cpp | 4 ++- src/test/unittests/base/StringTests.cpp | 42 ++++++++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/lib/base/String.cpp b/src/lib/base/String.cpp index cbaae56b..689295b6 100644 --- a/src/lib/base/String.cpp +++ b/src/lib/base/String.cpp @@ -232,7 +232,9 @@ splitString(String string, const char c) size_t head = 0; size_t separator = string.find(c); while (separator != String::npos) { - results.push_back(string.substr(head, separator - head)); + if (head!=separator) { + results.push_back(string.substr(head, separator - head)); + } head = separator + 1; separator = string.find(c, head); } diff --git a/src/test/unittests/base/StringTests.cpp b/src/test/unittests/base/StringTests.cpp index 8c76b578..29606417 100644 --- a/src/test/unittests/base/StringTests.cpp +++ b/src/test/unittests/base/StringTests.cpp @@ -101,7 +101,7 @@ TEST(StringTests, stringToUint) EXPECT_EQ(123, value); } -TEST(StringTests, splitString1) +TEST(StringTests, splitString_twoSeparator_returnThreeParts) { String string = "stub1:stub2:stub3"; @@ -113,7 +113,28 @@ TEST(StringTests, splitString1) EXPECT_EQ("stub3", results[2]); } -TEST(StringTests, splitString2) +TEST(StringTests, splitString_oneSeparator_returnTwoParts) +{ + String string = "stub1:stub2"; + + std::vector results = string::splitString(string, ':'); + + EXPECT_EQ(2, results.size()); + EXPECT_EQ("stub1", results[0]); + EXPECT_EQ("stub2", results[1]); +} + +TEST(StringTests, splitString_noSeparator_returnOriginalString) +{ + String string = "stub1"; + + std::vector results = string::splitString(string, ':'); + + EXPECT_EQ(1, results.size()); + EXPECT_EQ("stub1", results[0]); +} + +TEST(StringTests, splitString_tailSeparator_returnTwoParts) { String string = "stub1:stub2:"; @@ -124,13 +145,24 @@ TEST(StringTests, splitString2) EXPECT_EQ("stub2", results[1]); } -TEST(StringTests, splitString3) +TEST(StringTests, splitString_headSeparator_returnTwoParts) { - String string = "stub1"; + String string = ":stub1:stub2"; std::vector results = string::splitString(string, ':'); - EXPECT_EQ(1, results.size()); + EXPECT_EQ(2, results.size()); EXPECT_EQ("stub1", results[0]); + EXPECT_EQ("stub2", results[1]); } +TEST(StringTests, splitString_headAndTailSeparators_returnTwoParts) +{ + String string = ":stub1:stub2:"; + + std::vector results = string::splitString(string, ':'); + + EXPECT_EQ(2, results.size()); + EXPECT_EQ("stub1", results[0]); + EXPECT_EQ("stub2", results[1]); +}