c# - 在 C# 中是否可以通过单元测试或代码分析来确定类中是否使用了命名空间?

标签 c# unit-testing code-analysis static-code-analysis

作为一项业务规则,我们不允许在另一个命名空间内使用特定命名空间。

示例:

using X.A;  //Allowed
using X.B;  //Not allowed

namespace X.C
{
    const string abc = X.A.MyClass.ABC; //Allowed
    const string def = X.B.MyClass.DEF; //Not allowed, because we are using X.B

    public void MyMethod()
    {
        string ghi = X.A.MyClass.GHI; //Allowed
        string jkl = X.B.MyClass.JKL; //Not allowed because we are using X.B
        string mno = "X.B.MyClass.MNO"; //Allowed, because we are not accessing X.B
    }
}

是否可以通过单元测试、代码分析或两者来控制这一点,以便我们可以更轻松地执行此业务规则,而不是依赖于代码审查,因为代码审查很容易错过此类事情?假设这是可能的,你会如何去做呢?

最佳答案

使用工具 NDepend that let's write code rule through C# LINQ queries 可以实现这样的规则。 ,和check such rules live in Visual Studioin your Build Process .

具体来说,这样的规则可能如下所示:

warnif count > 0 from n in Namespaces where 
 n.IsUsing ("NUnit.Core.Extensibility") &&
(n.Name == @"NUnit.Core.Builders")
select new { n, n.NbLinesOfCode }
// the namespace NUnit.Core.Builders
// shouldn't use directly 
// the namespace NUnit.Core.Extensibility
// because (TODO insert your reason)

...并且可以在 Visual Studio 中实时编辑和执行/强制执行此规则。 NDepend Namespace Rule Edited in Visual Studio

实际上,您可以通过单击dependency graph来生成这样的代码规则。或来自dependency matrix :

NDepend Dependency Graph

这样的规则也可以在单元测试中编写和执行,因为 NDepend 提供了 API .

您可能也对我们的 white books concerning structuring code through namespaces and assemblies 感兴趣.

免责声明:我为 NDepend 工作。

关于c# - 在 C# 中是否可以通过单元测试或代码分析来确定类中是否使用了命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688275/

相关文章:

c# - 如何显式初始化枚举数组 [C#]

java - 测试读写文件系统的类时的单元测试最佳实践

code-analysis - 有没有人为FxCop/StyleCop创建任何很酷的规则?

c# - 为什么/optimize 在 C# 项目中生成比未启用此功能更多的代码分析警告?

c# - 获取泛型参数的类型

c# - 通过 DI 配置 Envers RevisionListener

c# - 将数组中的值与数组中之前的所有值进行比较的有效方法

unit-testing - 应该测试模型类吗?

html - Ruby Unit::测试通过忽略空格来比较 html 输出

prolog - 可视化 prolog 规则依赖关系