C# 流畅的断言,没有修饰
我想使用FluentAssertions测试所有未使用NoActionAttribute修饰的方法。(这将减少T4MVC自动生成为占位符的操作方法集。) 我的具体问题是将MethodInfoSelector方法链接在一起。我想这样写:C# 流畅的断言,没有修饰,c#,asp.net-mvc,unit-testing,t4mvc,fluent-assertions,C#,Asp.net Mvc,Unit Testing,T4mvc,Fluent Assertions,我想使用FluentAssertions测试所有未使用NoActionAttribute修饰的方法。(这将减少T4MVC自动生成为占位符的操作方法集。) 我的具体问题是将MethodInfoSelector方法链接在一起。我想这样写: public MethodInfoSelector AllActionMethods() { return TestControllerType.Methods() .ThatReturn<ActionResul
public MethodInfoSelector AllActionMethods() {
return TestControllerType.Methods()
.ThatReturn<ActionResult>()
.ThatAreNotDecoratedWith<NonActionAttribute>();
}
public static MethodInfoSelector ThatAreNotDecoratedWith<TAttribute>(this IEnumerable<MethodInfo> selectedMethods) {
return (MethodInfoSelector)(selectedMethods.Where(method => !method.GetCustomAttributes(false).OfType<TAttribute>().Any())); // this cast fails
}
公共方法信息选择器AllActionMethods(){
返回TestControllerType.Methods()
.ThatReturn()
.没有用()装饰的;
}
未装饰的公共静态方法信息选择器(此IEnumerable selectedMethods){
return(MethodInfoSelector)(selectedMethods.Where(method=>!method.GetCustomAttributes(false).OfType().Any());//此转换失败
}
要么强制转换失败,要么如果我将结果转换为IEnumberable,我就无法链接其他MethodInfoSelector方法
对于如何生成MethodInfoSelector或以不同的方法列出没有特定属性的方法这一根本问题,我将非常感谢您的帮助。Fluent断言目前没有公开的成员允许您这样做。您最好的解决方案是转到,打开问题或提交请求,以便在FA代码库中修复此问题 我意识到这可能被视为一个非答案,因此为了完整性,我将放弃您可以使用反射来解决此问题,尽管通常关于反射私人成员的免责声明适用。下面是一个这样的实现,它将让链接工作:
public static MethodInfoSelector ThatAreNotDecoratedWith<TAttribute>( this MethodInfoSelector selectedMethods)
{
IEnumerable<MethodInfo> methodsNotDecorated = selectedMethods.Where(
method =>
!method.GetCustomAttributes(false)
.OfType<TAttribute>()
.Any());
FieldInfo selectedMethodsField =
typeof (MethodInfoSelector).GetField("selectedMethods",
BindingFlags.Instance | BindingFlags.NonPublic);
selectedMethodsField.SetValue(selectedMethods, methodsNotDecorated);
return selectedMethods;
}
未装饰的公共静态方法信息选择器(此方法信息选择器已选择方法)
{
IEnumerable methods notdecorated=selectedMethods。其中(
方法=>
!method.GetCustomAttributes(false)
第()类
.Any());
FieldInfo SelectedMethods字段=
typeof(MethodInfoSelector).GetField(“selectedMethods”,
BindingFlags.Instance | BindingFlags.NonPublic);
selectedMethodsField.SetValue(selectedMethods,methodsNotDecorated);
返回所选方法;
}
谢谢@vossad,我尝试了代码并编译了它,但至少在一个地方我将结果用作NUnit测试用例,这导致NUnit崩溃。我认为你的第一个答案是最好的。我同意,我们还没有预料到这种需要。问题或拉取请求都可以解决此问题。