Falcon.SugarApi/Falcon.SugarApi.Test/StringExtendTest.cs

117 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace Falcon.SugarApi.Test
{
/// <summary>
/// 字符串扩展方法测试
/// </summary>
[TestClass]
public class StringExtendTest
{
[TestMethod]
public void TestSplit() {
var str = $"a,b.c;de。fg";
var strArr = str.SplitStr();
Assert.AreEqual(7,strArr.Length,"分割后长度应该为7");
str = "a,,, ,b ,c c,";
strArr = str.SplitStr();
Assert.AreEqual(3,strArr.Length,"分割后长度应该为3");
Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b",strArr[1]);
Assert.AreEqual("c c",strArr[2]);
str = null;
strArr = str.SplitStr();
Assert.IsNotNull(strArr);
Assert.AreEqual(0,strArr.Length);
//指定分隔符
str = $"a,b.c;de。fg";
strArr = str.SplitStr(',');
Assert.AreEqual(2,strArr.Length,"分割后长度应该为7");
Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b.c;de。fg",strArr[1]);
strArr = str.SplitStr(',','.');
Assert.AreEqual(3,strArr.Length,"分割后长度应该为7");
Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b",strArr[1]);
Assert.AreEqual("c;de。fg",strArr[2]);
}
/// <summary>
/// 测试ToDefault
/// </summary>
[TestMethod]
public void TestToDefault() {
var str = "";
var r = "";
r = str.ToDefault("abc");
Assert.AreEqual("abc",r);
str = null;
r = str.ToDefault("abc");
Assert.AreEqual("abc",r);
str = "123";
r = str.ToDefault("abc");
Assert.AreEqual("123",r);
}
/// <summary>
/// 检索子字符串测试
/// </summary>
[TestMethod]
public void TestSubstringEx() {
var str = "abcd33";
string r;
r = str.SubstringEx(str.Length + 1,1);
Assert.IsTrue(r == "");
r = str.SubstringEx(0,0);
Assert.IsTrue(r == "");
r = str.SubstringEx(3,-1);
Assert.IsTrue(r == "c");
r = str.SubstringEx(3,10);
Assert.IsTrue(r == "d33");
r = str.SubstringEx(-1,2);
Assert.IsTrue(r == "a");
r = str.SubstringEx(1,2);
Assert.IsTrue(r == "bc");
}
/// <summary>
/// 按一定长度分割字符串测试
/// </summary>
[TestMethod]
public void TestSplitByLength() {
string str;
string[] result;
str = "";
Assert.ThrowsException<ArgumentNullException>(() => { result = str.Split(5).ToArray(); });
str = "abc";
Assert.ThrowsException<Exception>(() => { result = str.Split(0).ToArray(); });
result = str.Split(1).ToArray();
Assert.IsTrue(result.Length == 3);
Assert.IsTrue(result[0] == "a");
Assert.IsTrue(result[1] == "b");
Assert.IsTrue(result[2] == "c");
result = str.Split(2).ToArray();
Assert.IsTrue(result.Length == 2);
Assert.IsTrue(result[0] == "ab");
Assert.IsTrue(result[1] == "c");
result = str.Split(3).ToArray();
Assert.IsTrue(result.Length == 1);
Assert.IsTrue(result[0] == "abc");
result = str.Split(4).ToArray();
Assert.IsTrue(result.Length == 1);
Assert.IsTrue(result[0] == "abc");
}
}
}