U:调整所有代码格式

This commit is contained in:
jimmy committed 2025-12-30 09:17:25 +08:00
1 parent d133bacf55
commit 155b67e831
342 files changed
+9431 -9868

No files matched your search

+8 -11
View File
@@ -118,9 +118,9 @@ public class CollectionExpandTests
// Act
var tree = items.ToTree(
idSelector: x => x.Id,
parentIdSelector: x => x.ParentId,
rootParentId: null
x => x.Id,
x => x.ParentId,
null
);
// Assert
@@ -243,10 +243,7 @@ public class CollectionExpandTests
var processedBatches = new List<int>();
// Act
items.ForEachBatch(10, batch =>
{
processedBatches.Add(batch.Count());
});
items.ForEachBatch(10, batch => { processedBatches.Add(batch.Count()); });
// Assert
Assert.AreEqual(3, processedBatches.Count);
@@ -618,9 +615,9 @@ public class CollectionExpandTests
// Act: 数据清洗流水线
var cleanedData = rawData
.WhereNotNull() // 去除 null
.DistinctBy(x => x) // 去重
.Where(x => x != "D") // 过滤不需要的数据
.WhereNotNull() // 去除 null
.DistinctBy(x => x) // 去重
.Where(x => x != "D") // 过滤不需要的数据
.ToList();
// Assert
@@ -629,4 +626,4 @@ public class CollectionExpandTests
}
#endregion
}
}
+10 -19
View File
@@ -67,10 +67,7 @@ public class CryptoHelperTests
var encrypted = CryptoHelper.AesEncrypt(plainText, correctPassword);
// Act & Assert
Assert.ThrowsException<CryptographicException>(() =>
{
CryptoHelper.AesDecrypt(encrypted, wrongPassword);
});
Assert.ThrowsException<CryptographicException>(() => { CryptoHelper.AesDecrypt(encrypted, wrongPassword); });
}
/// <summary>
@@ -79,10 +76,7 @@ public class CryptoHelperTests
[TestMethod]
public void AesEncrypt_EmptyString_ThrowsException()
{
Assert.ThrowsException<ArgumentNullException>(() =>
{
CryptoHelper.AesEncrypt("", "password");
});
Assert.ThrowsException<ArgumentNullException>(() => { CryptoHelper.AesEncrypt("", "password"); });
}
#endregion
@@ -155,10 +149,7 @@ public class CryptoHelperTests
var encrypted = CryptoHelper.RsaEncrypt(plainText, publicKey1);
// Act & Assert
Assert.ThrowsException<CryptographicException>(() =>
{
CryptoHelper.RsaDecrypt(encrypted, privateKey2);
});
Assert.ThrowsException<CryptographicException>(() => { CryptoHelper.RsaDecrypt(encrypted, privateKey2); });
}
#endregion
@@ -396,7 +387,7 @@ public class CryptoHelperTests
var password = "test";
// Act
var hash = CryptoHelper.HashPassword(password, saltSize: 32, iterations: 50000, hashSize: 64);
var hash = CryptoHelper.HashPassword(password, 32, 50000, 64);
var isValid = CryptoHelper.VerifyPassword(password, hash);
// Assert
@@ -514,7 +505,7 @@ public class CryptoHelperTests
// Arrange & Act
var str10 = CryptoHelper.GenerateRandomString(10);
var str20 = CryptoHelper.GenerateRandomString(20);
var strWithSpecial = CryptoHelper.GenerateRandomString(15, useSpecialChars: true);
var strWithSpecial = CryptoHelper.GenerateRandomString(15, true);
// Assert
Assert.AreEqual(10, str10.Length);
@@ -548,10 +539,10 @@ public class CryptoHelperTests
// Act
var password = CryptoHelper.GeneratePassword(
12,
requireDigit: true,
requireLowercase: true,
requireUppercase: true,
requireSpecialChar: false
true,
true,
true,
false
);
// Assert
@@ -745,4 +736,4 @@ public class CryptoHelperTests
}
#endregion
}
}
+6 -6
View File
@@ -413,8 +413,8 @@ public class DateTimeExpandTests
{
// Arrange
var saturday = new DateTime(2024, 3, 16); // 周六
var sunday = new DateTime(2024, 3, 17); // 周日
var monday = new DateTime(2024, 3, 18); // 周一
var sunday = new DateTime(2024, 3, 17); // 周日
var monday = new DateTime(2024, 3, 18); // 周一
// Act & Assert
Assert.IsTrue(saturday.IsWeekend());
@@ -502,7 +502,7 @@ public class DateTimeExpandTests
// Act: 舍入到 15 分钟间隔
var ceiling = dt.CeilingToMinutes(15); // 向上舍入到 14:30
var floor = dt.FloorToMinutes(15); // 向下舍入到 14:15
var floor = dt.FloorToMinutes(15); // 向下舍入到 14:15
// Assert
Assert.AreEqual(30, ceiling.Minute);
@@ -559,8 +559,8 @@ public class DateTimeExpandTests
{
// Arrange: 营业时间是工作日 9:00-18:00
var workdayMorning = new DateTime(2024, 3, 15, 10, 30, 0); // 周五 10:30
var weekend = new DateTime(2024, 3, 16, 10, 30, 0); // 周六 10:30
var afterHours = new DateTime(2024, 3, 15, 19, 30, 0); // 周五 19:30
var weekend = new DateTime(2024, 3, 16, 10, 30, 0); // 周六 10:30
var afterHours = new DateTime(2024, 3, 15, 19, 30, 0); // 周五 19:30
// Act & Assert
Assert.IsTrue(workdayMorning.IsWorkDay());
@@ -629,4 +629,4 @@ public class DateTimeExpandTests
}
#endregion
}
}
+3 -3
View File
@@ -410,7 +410,7 @@ public class EnumHelperTests
public void ToEnum_ConvertsIntToEnum()
{
// Arrange
int value = 3;
var value = 3;
// Act
var status = value.ToEnum<OrderStatus>();
@@ -517,7 +517,7 @@ public class EnumHelperTests
public void GetRandomExcept_ExcludesSpecifiedValues()
{
// Act: 多次获取随机值,确保不包含排除的值
for (int i = 0; i < 10; i++)
for (var i = 0; i < 10; i++)
{
var random = EnumHelper.GetRandomExcept(OrderStatus.Pending, OrderStatus.Cancelled);
@@ -631,4 +631,4 @@ public class EnumHelperTests
}
#endregion
}
}
+4 -13
View File
@@ -104,10 +104,7 @@ public class ExceptionExpandTests
public void Scenario_UseInBusinessLogic()
{
// Act: 执行可能失败的业务操作
var exception = Assert.ThrowsException<ExceptionExpand>(() =>
{
ProcessBusinessOperation(-1);
});
var exception = Assert.ThrowsException<ExceptionExpand>(() => { ProcessBusinessOperation(-1); });
// Assert
Assert.AreEqual(4001L, exception.ErrorCode);
@@ -132,10 +129,7 @@ public class ExceptionExpandTests
);
// Act: 捕获并检查异常链
var exception = Assert.ThrowsException<ExceptionExpand>(() =>
{
throw serviceException;
});
var exception = Assert.ThrowsException<ExceptionExpand>(() => { throw serviceException; });
// Assert: 验证异常链
Assert.AreEqual(5001L, exception.ErrorCode);
@@ -179,10 +173,7 @@ public class ExceptionExpandTests
/// </summary>
private void ProcessBusinessOperation(int userId)
{
if (userId <= 0)
{
throw new ExceptionExpand(4001L, "Invalid user ID", "User ID must be positive");
}
if (userId <= 0) throw new ExceptionExpand(4001L, "Invalid user ID", "User ID must be positive");
// 正常处理逻辑...
}
@@ -201,4 +192,4 @@ public class ExceptionExpandTests
}
#endregion
}
}
+17 -28
View File
@@ -125,10 +125,7 @@ public class GlobalTests
public void Get_UnregisteredService_ThrowsException()
{
// Act & Assert: 尝试获取未注册的服务应该抛出异常
var exception = Assert.ThrowsException<InvalidOperationException>(() =>
{
Global.Get<ILogger>();
});
var exception = Assert.ThrowsException<InvalidOperationException>(() => { Global.Get<ILogger>(); });
Assert.IsTrue(exception.Message.Contains("ILogger"));
}
@@ -235,10 +232,7 @@ public class GlobalTests
Global.RegisterTransient(() => new RequestContext());
// Act & Assert: 尝试更新瞬态服务应该抛出异常
Assert.ThrowsException<InvalidOperationException>(() =>
{
Global.Update(new RequestContext());
});
Assert.ThrowsException<InvalidOperationException>(() => { Global.Update(new RequestContext()); });
}
/// <summary>
@@ -311,7 +305,11 @@ public class GlobalTests
{
// Arrange: 订阅通知
var callCount = 0;
void Handler(ServiceChangedEventArgs<AppConfig> e) => callCount++;
void Handler(ServiceChangedEventArgs<AppConfig> e)
{
callCount++;
}
Global.Subscribe<AppConfig>(Handler);
Global.RegisterSingleton(new AppConfig { AppName = "App", Version = "1.0" });
@@ -343,7 +341,7 @@ public class GlobalTests
Assert.AreEqual(0, notificationCount); // 首次注册不触发
// Act: 使用 notifyIfExists = true 再次注册
Global.RegisterSingleton(new AppConfig { AppName = "App", Version = "2.0" }, notifyIfExists: true);
Global.RegisterSingleton(new AppConfig { AppName = "App", Version = "2.0" }, true);
// Assert: 应该触发通知
Assert.AreEqual(1, notificationCount);
@@ -387,10 +385,7 @@ public class GlobalTests
Assert.IsFalse(Global.IsRegistered<AppConfig>());
// 尝试获取应该失败
Assert.ThrowsException<InvalidOperationException>(() =>
{
Global.Get<AppConfig>();
});
Assert.ThrowsException<InvalidOperationException>(() => { Global.Get<AppConfig>(); });
}
/// <summary>
@@ -528,10 +523,7 @@ public class GlobalTests
var configHistory = new List<string>();
// 订阅配置变更
Global.Subscribe<AppConfig>(e =>
{
configHistory.Add($"v{e.OldValue?.Version} -> v{e.NewValue.Version}");
});
Global.Subscribe<AppConfig>(e => { configHistory.Add($"v{e.OldValue?.Version} -> v{e.NewValue.Version}"); });
// Act: 注册初始配置
Global.RegisterSingleton(new AppConfig { AppName = "MyApp", Version = "1.0" });
@@ -564,16 +556,10 @@ public class GlobalTests
var logEntries = new List<string>();
// UI 组件订阅
Global.Subscribe<UserSession>(e =>
{
uiUpdates.Add($"Display: {e.NewValue.Username}");
});
Global.Subscribe<UserSession>(e => { uiUpdates.Add($"Display: {e.NewValue.Username}"); });
// 日志组件订阅
Global.Subscribe<UserSession>(e =>
{
logEntries.Add($"Session changed at {e.ChangedAt:HH:mm:ss}");
});
Global.Subscribe<UserSession>(e => { logEntries.Add($"Session changed at {e.ChangedAt:HH:mm:ss}"); });
// Act: 用户登录
Global.RegisterSingleton(new UserSession
@@ -620,7 +606,10 @@ public class GlobalTests
private class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine($"[LOG] {message}");
public void Log(string message)
{
Console.WriteLine($"[LOG] {message}");
}
}
private class UserSession
@@ -640,4 +629,4 @@ public class GlobalTests
}
#endregion
}
}
+35 -35
View File
@@ -30,7 +30,7 @@ public class JsonHelperTests
var json = JsonHelper.ToJson(person);
// Assert
Assert.IsTrue(json.Contains("\"name\": \"John Doe\"")); // camelCase
Assert.IsTrue(json.Contains("\"name\": \"John Doe\"")); // camelCase
Assert.IsTrue(json.Contains("\"age\": 30"));
Assert.IsTrue(json.Contains("\"email\": \"john@example.com\""));
}
@@ -54,7 +54,7 @@ public class JsonHelperTests
// Assert: 属性名应该是 camelCase
Assert.IsTrue(json.Contains("\"appName\""));
Assert.IsTrue(json.Contains("\"maxConnections\""));
Assert.IsFalse(json.Contains("\"AppName\"")); // 不应该是 PascalCase
Assert.IsFalse(json.Contains("\"AppName\"")); // 不应该是 PascalCase
}
/// <summary>
@@ -85,12 +85,12 @@ public class JsonHelperTests
{
// Arrange
var json = """
{
"name": "Alice",
"age": 28,
"email": "alice@example.com"
}
""";
{
"name": "Alice",
"age": 28,
"email": "alice@example.com"
}
""";
// Act
var person = JsonHelper.FromJson<Person>(json);
@@ -110,11 +110,11 @@ public class JsonHelperTests
{
// Arrange: JSON 使用 camelCase
var json = """
{
"appName": "TestApp",
"maxConnections": 50
}
""";
{
"appName": "TestApp",
"maxConnections": 50
}
""";
// Act
var config = JsonHelper.FromJson<AppConfig>(json);
@@ -148,7 +148,7 @@ public class JsonHelperTests
// Assert: 枚举应该序列化为字符串(camelCase)
Assert.IsTrue(json.Contains("\"active\""));
Assert.IsTrue(json.Contains("\"high\""));
Assert.IsFalse(json.Contains("0")); // 不应该是数字
Assert.IsFalse(json.Contains("0")); // 不应该是数字
Assert.IsFalse(json.Contains("1"));
}
@@ -160,11 +160,11 @@ public class JsonHelperTests
{
// Arrange
var json = """
{
"status": "active",
"priority": "low"
}
""";
{
"status": "active",
"priority": "low"
}
""";
// Act
var data = JsonHelper.FromJson<DataWithEnum>(json);
@@ -204,11 +204,11 @@ public class JsonHelperTests
{
// Arrange
var json = """
{
"serverIp": "192.168.1.1",
"clientIp": "10.0.0.5"
}
""";
{
"serverIp": "192.168.1.1",
"clientIp": "10.0.0.5"
}
""";
// Act
var networkInfo = JsonHelper.FromJson<NetworkInfo>(json);
@@ -374,16 +374,16 @@ public class JsonHelperTests
// 模拟 API 调用后收到响应
var responseJson = """
{
"success": true,
"data": {
"name": "New User",
"age": 25,
"email": "newuser@example.com"
},
"message": "User created successfully"
}
""";
{
"success": true,
"data": {
"name": "New User",
"age": 25,
"email": "newuser@example.com"
},
"message": "User created successfully"
}
""";
var response = JsonHelper.FromJson<ApiResponse<Person>>(responseJson);
@@ -507,4 +507,4 @@ public class JsonHelperTests
}
#endregion
}
}
+5 -20
View File
@@ -186,19 +186,13 @@ public class ReflectionHelperTests
// Act: 使用 ReflectionHelper(有缓存)
var sw1 = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
_ = ReflectionHelper.GetPropertyValue(user, nameof(User.Name));
}
for (var i = 0; i < iterations; i++) _ = ReflectionHelper.GetPropertyValue(user, nameof(User.Name));
sw1.Stop();
// Act: 使用原生反射(无缓存)
var propertyInfo = typeof(User).GetProperty(nameof(User.Name))!;
var sw2 = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
_ = propertyInfo.GetValue(user);
}
for (var i = 0; i < iterations; i++) _ = propertyInfo.GetValue(user);
sw2.Stop();
// Assert: ReflectionHelper 应该比直接反射快(由于缓存和表达式树)
@@ -377,7 +371,7 @@ public class ReflectionHelperTests
var target = new UserDto();
// Act
ReflectionHelper.CopyProperties(source, target, ignoreCase: true);
ReflectionHelper.CopyProperties(source, target, true);
// Assert
Assert.AreEqual("Alice", target.Name);
@@ -565,12 +559,8 @@ public class ReflectionHelperTests
// Act: 实例化并执行插件
foreach (var pluginType in plugins)
{
if (ReflectionHelper.CreateInstance(pluginType) is ITestService plugin)
{
plugin.Execute(); // 输出:Executing test service
}
}
}
[TestMethod]
@@ -610,9 +600,7 @@ public class ReflectionHelperTests
// Act: 动态更新属性
foreach (var (propertyName, value) in propertyUpdates)
{
ReflectionHelper.SetPropertyValue(user, propertyName, value);
}
// Assert
Assert.AreEqual("Updated Bob", user.Name);
@@ -631,10 +619,7 @@ public class ReflectionHelperTests
foreach (var property in properties)
{
var description = ReflectionHelper.GetAttribute<System.ComponentModel.DescriptionAttribute>(property);
if (description != null)
{
validationMessages[property.Name] = $"{description.Description}不能为空";
}
if (description != null) validationMessages[property.Name] = $"{description.Description}不能为空";
}
// Assert
@@ -671,4 +656,4 @@ public class ReflectionHelperTests
}
#endregion
}
}
+14 -26
View File
@@ -125,10 +125,7 @@ public class ResultTests
var executed = false;
// Act
var result = Result.Try(() =>
{
executed = true;
});
var result = Result.Try(() => { executed = true; });
// Assert
Assert.IsTrue(result.IsSuccess);
@@ -142,10 +139,7 @@ public class ResultTests
public void Try_FailingAction_ReturnsFailure()
{
// Act
var result = Result.Try(() =>
{
throw new InvalidOperationException("Operation failed");
});
var result = Result.Try(() => { throw new InvalidOperationException("Operation failed"); });
// Assert
Assert.IsTrue(result.IsFailure);
@@ -188,10 +182,7 @@ public class ResultTests
public async Task TryAsync_SuccessfulTask_ReturnsSuccess()
{
// Act
var result = await Result.TryAsync(async () =>
{
await Task.Delay(10);
});
var result = await Result.TryAsync(async () => { await Task.Delay(10); });
// Assert
Assert.IsTrue(result.IsSuccess);
@@ -310,10 +301,7 @@ public class ResultTests
var result = Result.Failure<int>(exception);
// Act & Assert
var thrown = Assert.ThrowsException<InvalidOperationException>(() =>
{
result.GetOrThrow();
});
var thrown = Assert.ThrowsException<InvalidOperationException>(() => { result.GetOrThrow(); });
Assert.AreSame(exception, thrown);
}
@@ -566,8 +554,8 @@ public class ResultTests
// Act
var message = result.Match(
onSuccess: value => $"Success: {value}",
onFailure: (ex, msg) => $"Error: {msg}"
value => $"Success: {value}",
(ex, msg) => $"Error: {msg}"
);
// Assert
@@ -585,8 +573,8 @@ public class ResultTests
// Act
var message = result.Match(
onSuccess: value => $"Success: {value}",
onFailure: (ex, msg) => $"Error: {msg}"
value => $"Success: {value}",
(ex, msg) => $"Error: {msg}"
);
// Assert
@@ -609,9 +597,9 @@ public class ResultTests
// Act: 使用 LINQ 查询语法
var combined = from x in result1
from y in result2
where x > 0 && y > 0
select x + y;
from y in result2
where x > 0 && y > 0
select x + y;
// Assert
Assert.IsTrue(combined.IsSuccess);
@@ -630,8 +618,8 @@ public class ResultTests
// Act
var combined = from x in result1
from y in result2
select x + y;
from y in result2
select x + y;
// Assert
Assert.IsTrue(combined.IsFailure);
@@ -877,4 +865,4 @@ public class ResultTests
}
#endregion
}
}
+16 -19
View File
@@ -69,17 +69,14 @@ public class StringExpandTests
var invalidUrls = new[]
{
"not a url",
"example.com", // 缺少协议
"http://", // 不完整
"", // 空字符串
"://invalid" // 无效格式
"example.com", // 缺少协议
"http://", // 不完整
"", // 空字符串
"://invalid" // 无效格式
};
// Act & Assert
foreach (var url in invalidUrls)
{
Assert.IsFalse(url.IsValidUrl(), $"'{url}' should be invalid");
}
foreach (var url in invalidUrls) Assert.IsFalse(url.IsValidUrl(), $"'{url}' should be invalid");
}
#endregion
@@ -281,22 +278,22 @@ public class StringExpandTests
{
["Port"] = "8080",
["Timeout"] = "30",
["MaxRetries"] = "invalid", // 无效值
["MaxRetries"] = "invalid", // 无效值
["Price"] = "99.99",
["Discount"] = "0.15"
};
// Act: 解析配置值
var port = config["Port"].ToInt(80); // 默认 80
var timeout = config["Timeout"].ToInt(60); // 默认 60
var maxRetries = config["MaxRetries"].ToInt(3); // 无效值,使用默认 3
var port = config["Port"].ToInt(80); // 默认 80
var timeout = config["Timeout"].ToInt(60); // 默认 60
var maxRetries = config["MaxRetries"].ToInt(3); // 无效值,使用默认 3
var price = config["Price"].ToDouble(0.0);
var discount = config["Discount"].ToDouble(0.0);
// Assert
Assert.AreEqual(8080, port);
Assert.AreEqual(30, timeout);
Assert.AreEqual(3, maxRetries); // 使用了默认值
Assert.AreEqual(3, maxRetries); // 使用了默认值
Assert.AreEqual(99.99, price);
Assert.AreEqual(0.15, discount);
}
@@ -332,8 +329,8 @@ public class StringExpandTests
public void Scenario_SafelyParseUserInput()
{
// Arrange: 模拟用户输入(可能无效)
string? userAgeInput = "25";
string? userWeightInput = "invalid";
var userAgeInput = "25";
var userWeightInput = "invalid";
string? userHeightInput = null;
// Act: 安全解析
@@ -344,8 +341,8 @@ public class StringExpandTests
// Assert
Assert.IsNotNull(age);
Assert.AreEqual(25, age.Value);
Assert.IsNull(weight); // 无效输入
Assert.IsNull(height); // null 输入
Assert.IsNull(weight); // 无效输入
Assert.IsNull(height); // null 输入
// 使用默认值的版本
var ageWithDefault = userAgeInput.ToInt(18);
@@ -353,7 +350,7 @@ public class StringExpandTests
var heightWithDefault = userHeightInput.ToDouble(170.0);
Assert.AreEqual(25, ageWithDefault);
Assert.AreEqual(70.0, weightWithDefault); // 使用默认值
Assert.AreEqual(70.0, weightWithDefault); // 使用默认值
Assert.AreEqual(170.0, heightWithDefault); // 使用默认值
}
@@ -389,4 +386,4 @@ public class StringExpandTests
}
#endregion
}
}
+6 -17
View File
@@ -132,7 +132,7 @@ public class SystemHelperTests
var allocatedPorts = new List<int>();
// Act: 为每个服务器分配端口
for (int i = 0; i < serverCount; i++)
for (var i = 0; i < serverCount; i++)
{
var port = SystemHelper.GetAvailablePort();
allocatedPorts.Add(port);
@@ -162,11 +162,9 @@ public class SystemHelperTests
void PrivilegedOperation()
{
if (!SystemHelper.IsAdministrator())
{
throw new UnauthorizedAccessException(
"This operation requires administrator privileges"
);
}
// 执行需要管理员权限的操作...
Console.WriteLine("Executing privileged operation");
@@ -182,10 +180,7 @@ public class SystemHelperTests
else
{
// 如果不是管理员,应该抛出异常
Assert.ThrowsException<UnauthorizedAccessException>(() =>
{
PrivilegedOperation();
});
Assert.ThrowsException<UnauthorizedAccessException>(() => { PrivilegedOperation(); });
}
}
@@ -202,7 +197,7 @@ public class SystemHelperTests
try
{
// Act: 启动多个测试服务器
for (int i = 0; i < 3; i++)
for (var i = 0; i < 3; i++)
{
var port = SystemHelper.GetAvailablePort();
var server = new TestServer($"TestServer{i + 1}", port);
@@ -223,10 +218,7 @@ public class SystemHelperTests
finally
{
// Cleanup: 停止所有测试服务器
foreach (var server in testServers)
{
server.Stop();
}
foreach (var server in testServers) server.Stop();
}
}
@@ -242,10 +234,7 @@ public class SystemHelperTests
var ports = new List<int>();
// Act: 收集端口样本
for (int i = 0; i < sampleSize; i++)
{
ports.Add(SystemHelper.GetAvailablePort());
}
for (var i = 0; i < sampleSize; i++) ports.Add(SystemHelper.GetAvailablePort());
// Assert: 验证所有端口都在合理范围内
// 动态端口范围通常是 49152-65535
@@ -333,4 +322,4 @@ public class SystemHelperTests
}
#endregion
}
}
+28 -55
View File
@@ -24,10 +24,7 @@ public class ValidationHelperTests
};
// Act & Assert
foreach (var email in validEmails)
{
Assert.IsTrue(ValidationHelper.IsValidEmail(email), $"Failed for: {email}");
}
foreach (var email in validEmails) Assert.IsTrue(ValidationHelper.IsValidEmail(email), $"Failed for: {email}");
}
[TestMethod]
@@ -46,9 +43,7 @@ public class ValidationHelperTests
// Act & Assert
foreach (var email in invalidEmails)
{
Assert.IsFalse(ValidationHelper.IsValidEmail(email), $"Should fail for: {email}");
}
}
[TestMethod]
@@ -97,9 +92,7 @@ public class ValidationHelperTests
// Act & Assert
foreach (var mobile in validMobiles)
{
Assert.IsTrue(ValidationHelper.IsValidChinaMobile(mobile), $"Failed for: {mobile}");
}
}
[TestMethod]
@@ -109,17 +102,15 @@ public class ValidationHelperTests
var invalidMobiles = new[]
{
"",
"1234567890", // 10 位
"123456789012", // 12 位
"12812345678", // 第二位是 2
"abcdefghijk" // 非数字
"1234567890", // 10 位
"123456789012", // 12 位
"12812345678", // 第二位是 2
"abcdefghijk" // 非数字
};
// Act & Assert
foreach (var mobile in invalidMobiles)
{
Assert.IsFalse(ValidationHelper.IsValidChinaMobile(mobile), $"Should fail for: {mobile}");
}
}
[TestMethod]
@@ -150,9 +141,7 @@ public class ValidationHelperTests
// Act & Assert
foreach (var mobile in validMobiles)
{
Assert.IsTrue(ValidationHelper.IsValidInternationalMobile(mobile), $"Failed for: {mobile}");
}
}
#endregion
@@ -165,8 +154,8 @@ public class ValidationHelperTests
// Arrange: 测试有效的身份证号(包含正确的校验码)
var validIdCards = new[]
{
"11010519491231002X", // 北京,1949年12月31日,校验码 X
"110105194912310021" // 北京,1949年12月31日,校验码 1
"11010519491231002X", // 北京,1949年12月31日,校验码 X
"110105194912310021" // 北京,1949年12月31日,校验码 1
};
// Act & Assert
@@ -184,9 +173,9 @@ public class ValidationHelperTests
var invalidIdCards = new[]
{
"",
"12345", // 太短
"123456789012345678", // 格式不对(日期无效)
"11010519491399002X" // 无效日期(99号)
"12345", // 太短
"123456789012345678", // 格式不对(日期无效)
"11010519491399002X" // 无效日期(99号)
};
// Act & Assert
@@ -217,8 +206,8 @@ public class ValidationHelperTests
public void ExtractGenderFromIdCard_ValidIdCard_ReturnsCorrectGender()
{
// Arrange
var maleIdCard = "110105199001150011"; // 倒数第二位是 1(奇数)
var femaleIdCard = "110105199001150024"; // 倒数第二位是 2(偶数)
var maleIdCard = "110105199001150011"; // 倒数第二位是 1(奇数)
var femaleIdCard = "110105199001150024"; // 倒数第二位是 2(偶数)
// Act
var maleGender = ValidationHelper.ExtractGenderFromIdCard(maleIdCard);
@@ -246,10 +235,7 @@ public class ValidationHelperTests
};
// Act & Assert
foreach (var url in validUrls)
{
Assert.IsTrue(ValidationHelper.IsValidUrl(url), $"Failed for: {url}");
}
foreach (var url in validUrls) Assert.IsTrue(ValidationHelper.IsValidUrl(url), $"Failed for: {url}");
}
[TestMethod]
@@ -260,16 +246,13 @@ public class ValidationHelperTests
{
"",
"not-a-url",
"ftp://example.com", // 不是 HTTP/HTTPS
"ftp://example.com", // 不是 HTTP/HTTPS
"//example.com",
"example.com" // 缺少协议
"example.com" // 缺少协议
};
// Act & Assert
foreach (var url in invalidUrls)
{
Assert.IsFalse(ValidationHelper.IsValidUrl(url), $"Should fail for: {url}");
}
foreach (var url in invalidUrls) Assert.IsFalse(ValidationHelper.IsValidUrl(url), $"Should fail for: {url}");
}
[TestMethod]
@@ -389,9 +372,7 @@ public class ValidationHelperTests
// Act & Assert
foreach (var password in strongPasswords)
{
Assert.IsTrue(ValidationHelper.IsStrongPassword(password), $"Failed for: {password}");
}
}
[TestMethod]
@@ -400,18 +381,16 @@ public class ValidationHelperTests
// Arrange
var weakPasswords = new[]
{
"12345678", // 只有数字
"abcdefgh", // 只有小写
"ABCDEFGH", // 只有大写
"Abc123", // 太短
"Abcdefgh", // 缺少数字和特殊字符
"12345678", // 只有数字
"abcdefgh", // 只有小写
"ABCDEFGH", // 只有大写
"Abc123", // 太短
"Abcdefgh" // 缺少数字和特殊字符
};
// Act & Assert
foreach (var password in weakPasswords)
{
Assert.IsFalse(ValidationHelper.IsStrongPassword(password), $"Should fail for: {password}");
}
}
[TestMethod]
@@ -447,10 +426,7 @@ public class ValidationHelperTests
};
// Act & Assert
foreach (var ip in validIPs)
{
Assert.IsTrue(ValidationHelper.IsValidIPv4(ip), $"Failed for: {ip}");
}
foreach (var ip in validIPs) Assert.IsTrue(ValidationHelper.IsValidIPv4(ip), $"Failed for: {ip}");
}
[TestMethod]
@@ -460,17 +436,14 @@ public class ValidationHelperTests
var invalidIPs = new[]
{
"",
"256.1.1.1", // 超出范围
"192.168.1", // 不完整
"192.168.1.1.1", // 太多段
"256.1.1.1", // 超出范围
"192.168.1", // 不完整
"192.168.1.1.1", // 太多段
"not.an.ip.address"
};
// Act & Assert
foreach (var ip in invalidIPs)
{
Assert.IsFalse(ValidationHelper.IsValidIPv4(ip), $"Should fail for: {ip}");
}
foreach (var ip in invalidIPs) Assert.IsFalse(ValidationHelper.IsValidIPv4(ip), $"Should fail for: {ip}");
}
#endregion
@@ -499,7 +472,7 @@ public class ValidationHelperTests
public void ValidateAll_OneFails_ReturnsFailure()
{
// Arrange
var email = "ab"; // 太短
var email = "ab"; // 太短
// Act
var result = ValidationHelper.ValidateAll(
@@ -621,4 +594,4 @@ public class ValidationHelperTests
}
#endregion
}
}