如何检查类的所有公共方法是否为虚拟方法(How to check that all public methods of a class are virtual)

在.net项目中,有很多实体在c#中实现。 使用过的库(saser实体的nservicebus)的要求是所有访问方法都要声明为public和virtual,否则在部署过程中会失效。

在单元测试阶段检查实体的访问方法是虚拟的是合理的,sa部署可能需要花费很多时间(在它被发现之前)

有没有人知道检查类中的所有公共方法是否在nunit测试中声明为虚拟的好方法?

In .net project there are a lot of entities implemented in c#. The requirement of used library (nservicebus for saga entities) is that all access methods to be declared as public and virtual, otherwise it failes during the deploy process.

It's reasonable to check that an entity's access methods are virtual on unit testing stage, s.a. deploy could take a lot of time (before it would be discovered)

Does anyone knows a good way to check that all public methods in a class are declared virtual in an nunit test?

最满意答案

我使用相同的测试来验证,游戏引擎包装器将所有公共方法都视为虚拟。 它使测试更容易,并可以大大减少反馈时间。 这些方法我放在特殊的类DesignTests ,我在那里测试,例如,我的项目中没有违反约定。 有一些复杂的东西, FxCop无法检测到。 你可以看到下面的代码:

[Test] public void AllPublicMethodsInUnityFacade_ShouldBeVirtual() { var allPublicMethods = typeof(UnityFacade).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); Assert.IsTrue(allPublicMethods.All(method => method.IsVirtual), string.Join(", ", allPublicMethods .Where(method => !method.IsVirtual) .Select(method => method.Name)) + " is not virtual"); }

I use kind of the same test to verify, that game engine wrapper has all public method as virtual. It makes testing easier and can dramatically reduce feedback time. Such methods I place under special class DesignTests, where I test, for example, that conventions are not violated in my projects. There are complex things, that FxCop can't detect. You can see the code below:

[Test] public void AllPublicMethodsInUnityFacade_ShouldBeVirtual() { var allPublicMethods = typeof(UnityFacade).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); Assert.IsTrue(allPublicMethods.All(method => method.IsVirtual), string.Join(", ", allPublicMethods .Where(method => !method.IsVirtual) .Select(method => method.Name)) + " is not virtual"); }

更多推荐