URLがルートテーブルに従って適切なコントローラーとアクションにマップされ、ターゲットのアクションメソッドとコントローラーが関連するアセンブリ内に存在することを確認するために、いくつかの単体テストを設定しようとしています。
私が抱えている唯一の残りの問題は、ActionNameAttribute
ダッシュ区切りのアクション名マッピングを有効にするために適用されたアクションメソッドの存在をテストすることです。たとえば、「お問い合わせ」フォームの URL:/contact-us
フォームの ContactUs メソッドにマップしますコントローラーは、ContactUs メソッドのシグネチャが次のように定義されているためです。
[ActionName("contact-us")]
public ActionResult ContactUs()
各テスト内で実行している次のメソッドを設定しました。これは、アクション メソッド名がで再定義されていないActionNameAttribute
すべてのケースで機能します。
private static bool ActionIsDefinedOnController(string expectedActionName, string controllerName, string assemblyName)
{
var thisControllerType = Type.GetType(AssemblyQualifiedName(controllerName, assemblyName), false, true);
if (thisControllerType == null)
return false;
var allThisControllersActions = thisControllerType.GetMethods().Select(m => m.Name.ToLower());
if( allThisControllersActions.Contains(expectedActionName.ToLower()))
return true;
var methods = thisControllerType.GetMethods();
//If we've so far failed to find the method, look for methods with ActionName attributes, and check in those values:
foreach (var method in methods)
{
if (Attribute.IsDefined(method, typeof(ActionNameAttribute))
{
var a = (ActionNameAttribute) Attribute.GetCustomAttribute(method, typeof (ActionNameAttribute));
if (a.Name == expectedActionName)
return true;
}
}
return false;
}
...しかし、メソッドの名前が で再定義されるたびに、デバッグセッションでカスタム属性のリストに属性が表示されていてもActionNameAttribute
、チェックAttribute.IsDefined(method, typeof(ActionNameAttribute)
は失敗します ( を返します):false
パスするはずのこのチェックが失敗するのはなぜですか?
私は別のチェックを構築することができました:
更新最初にここに間違ったコードを貼り付けていましたが、これが改訂されたものです:
List<string> customAttributes = method.GetCustomAttributes(false).Select(a => a.ToString()).ToList();
if (customAttributes.Contains("System.Web.Mvc.ActionNameAttribute"))
{
var a = (ActionNameAttribute) Attribute.GetCustomAttribute(method, typeof (ActionNameAttribute));
if (a.Name == expectedActionName)
return true;
}
...そして今、私の条件はActionNameAttribute
適用されるケースをキャッチしていますが、Attribute.GetCustomAttribute()
null を返すようになりました。そのため、アクション名の値をチェックして、期待値と比較することはできません... ああ!