【发布时间】:2013-03-01 02:58:28
【问题描述】:
使用自定义 FXCop 规则,我想确保在每个单元测试的顶部调用一个方法,并且所有单元测试代码都是传递给该方法的 Action 的一部分。基本上我想要这个:
[TestMethod]
public void SomeTest()
{
Run(() => {
// ALL unit test code has to be inside a Run call
});
}
确保确实调用了 Run 并不难:
public override void VisitMethod(Method member)
{
var method = member as Method;
if (method == null || method.Attributes == null)
return;
if (method.Attributes.Any(attr => attr.Type.Name.Name == "TestMethodAttribute") &&
method.Instructions != null)
{
if (!method.Instructions.Any(i => i.OpCode == OpCode.Call || i.Value.ToString() == "MyNamespace.Run"))
{
this.Problems.Add(new Problem(this.GetResolution(), method.GetUnmangledNameWithoutTypeParameters()));
}
base.VisitMethod(method);
}
诀窍是确保在运行语句之前没有在测试顶部调用的内容。过去几个小时我一直在研究 Instructions 集合以获取模式和试图了解如何在代码中有效地使用 Body.Statements 集合。
这也可以作为一个简单的 IL 问题提出。我想知道一个我可以验证的特定模式将接受这个:
public void SomeTest()
{
Run(() => {
// Potentially lots of code
});
}
但会拒绝以下任何一个:
public void SomeTest()
{
String blah = “no code allowed before Run”;
Run(() => {
// Potentially lots of code
});
}
public void SomeTest()
{
Run(() => {
// Potentially lots of code
});
String blah = “no code allowed after Run”;
}
【问题讨论】:
-
您也许可以使用表达式树来实现这一点。我会尝试发布一个示例,可能是。
-
如何使用表达式树? FxCop 只能访问 IL,不能访问源代码。
标签: c# visual-studio-2010 analysis fxcop il