You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过.editorconfig为C#单元测试设置不同命名风格?

为C#单元测试在.editorconfig中指定独立命名风格

可以实现,以下是两种满足需求的方案,均支持在单个.editorconfig文件中配置:

方案1:识别带[Test]特性的测试方法

通过.editorconfig的命名规则,精准匹配带有[Test](或[Fact]/[Theory]等测试框架特性)的方法,为其单独设置下划线命名风格:

# 全局方法命名规则(非测试方法)
dotnet_naming_rule.methods_pascal_case.severity = warning
dotnet_naming_rule.methods_pascal_case.symbols = methods
dotnet_naming_rule.methods_pascal_case.style = pascal_case_style

dotnet_naming_symbols.methods.applicable_kinds = method
dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected

dotnet_naming_style.pascal_case_style.capitalization = pascal_case

# 测试方法命名规则(匹配指定测试特性)
dotnet_naming_rule.test_methods_snake_case.severity = warning
dotnet_naming_rule.test_methods_snake_case.symbols = test_methods
dotnet_naming_rule.test_methods_snake_case.style = snake_case_style

dotnet_naming_symbols.test_methods.applicable_kinds = method
dotnet_naming_symbols.test_methods.applicable_accessibilities = public, internal
dotnet_naming_symbols.test_methods.required_attributes = Test, Fact, Theory # 根据你的测试框架调整特性名

dotnet_naming_style.snake_case_style.capitalization = snake_case
dotnet_naming_style.snake_case_style.word_separator = _

该配置会让dotnet format仅对带有指定测试特性的方法保留下划线命名,其他方法仍遵循PascalCase规则。

方案2:排除测试项目/文件

如果特性识别的方式不符合需求,可通过文件路径匹配,为测试项目的代码单独设置命名规则:

# 全局方法命名规则
dotnet_naming_rule.methods_pascal_case.severity = warning
dotnet_naming_rule.methods_pascal_case.symbols = methods
dotnet_naming_rule.methods_pascal_case.style = pascal_case_style

dotnet_naming_symbols.methods.applicable_kinds = method
dotnet_naming_style.pascal_case_style.capitalization = pascal_case

# 针对测试文件/项目的规则(路径匹配可根据实际项目结构调整)
[**/*Tests/**/*.cs]
dotnet_naming_rule.methods_snake_case.severity = warning
dotnet_naming_rule.methods_snake_case.symbols = all_methods
dotnet_naming_rule.methods_snake_case.style = snake_case_style

dotnet_naming_symbols.all_methods.applicable_kinds = method
dotnet_naming_style.snake_case_style.capitalization = snake_case
dotnet_naming_style.snake_case_style.word_separator = _

这里通过[**/*Tests/**/*.cs]匹配所有Tests目录下的C#文件,给这些文件内的所有方法启用下划线命名规则,覆盖全局的PascalCase设置。

注意:推荐使用.NET 6及以上版本的dotnet format,对这类规则的兼容性更好。

内容的提问来源于stack exchange,提问作者Thomas Mulder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:15:31