string_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package buildin
  2. import "testing"
  3. func TestSplitStringByLength(t *testing.T) {
  4. // 测试用例1:字符串长度小于 maxLength
  5. str := "Hello"
  6. maxLength := 10
  7. expected := []string{"Hello"}
  8. result := SplitStringByLength(str, maxLength)
  9. if len(result) != len(expected) {
  10. t.Errorf("Expected %d elements, but got %d", len(expected), len(result))
  11. }
  12. for i := range result {
  13. if result[i] != expected[i] {
  14. t.Errorf("Expected %s, but got %s", expected[i], result[i])
  15. }
  16. }
  17. // 测试用例2:字符串长度大于 maxLength
  18. str = "你好,Hello,世界!"
  19. maxLength = 5
  20. expected = []string{"你好,", "Hello", ",世界", "!"}
  21. result = SplitStringByLength(str, maxLength)
  22. if len(result) != len(expected) {
  23. t.Errorf("Expected %d elements, but got %d", len(expected), len(result))
  24. }
  25. for i := range result {
  26. if result[i] != expected[i] {
  27. t.Errorf("Expected %s, but got %s", expected[i], result[i])
  28. }
  29. }
  30. }
  31. func TestRandString(t *testing.T) {
  32. // 测试用例1:生成长度为10的随机字符串
  33. n := 10
  34. result := RandString(n)
  35. if len(result) != n {
  36. t.Errorf("Expected string length %d, but got %d", n, len(result))
  37. }
  38. // 测试用例2:生成长度为20的随机字符串
  39. n = 20
  40. result = RandString(n)
  41. if len(result) != n {
  42. t.Errorf("Expected string length %d, but got %d", n, len(result))
  43. }
  44. // 测试用例3:生成长度为0的随机字符串
  45. n = 0
  46. result = RandString(n)
  47. if len(result) != n {
  48. t.Errorf("Expected string length %d, but got %d", n, len(result))
  49. }
  50. }
  51. func BenchmarkRandString(b *testing.B) {
  52. n := 10
  53. for i := 0; i < b.N; i++ {
  54. RandString(n)
  55. }
  56. }
  57. func TestRandNumberString(t *testing.T) {
  58. // 测试用例1:生成3位数字字符串
  59. bit := uint8(3)
  60. result := RandNumberString(bit)
  61. if len(result) != int(bit) {
  62. t.Errorf("Expected string length %d, but got %d", bit, len(result))
  63. }
  64. // 测试用例2:生成5位数字字符串
  65. bit = uint8(5)
  66. result = RandNumberString(bit)
  67. if len(result) != int(bit) {
  68. t.Errorf("Expected string length %d, but got %d", bit, len(result))
  69. }
  70. // 测试用例3:生成0位数字字符串
  71. bit = uint8(0)
  72. result = RandNumberString(bit)
  73. if len(result) != int(bit) {
  74. t.Errorf("Expected string length %d, but got %d", bit, len(result))
  75. }
  76. }
  77. func BenchmarkRandNumberString(b *testing.B) {
  78. bit := uint8(10)
  79. for i := 0; i < b.N; i++ {
  80. RandNumberString(bit)
  81. }
  82. }