0

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

Action.IsDefined の失敗

パスするはずのこのチェックが失敗するのはなぜですか?

私は別のチェックを構築することができました:

更新最初にここに間違ったコードを貼り付けていましたが、これが改訂されたものです:

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 を返すようになりました。そのため、アクション名の値をチェックして、期待値と比較することはできません... ああ!

4

1 に答える 1

2

私はただ持っているでしょう:

//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)
{
    var attr = method.GetCustomAttribute<System.Web.Mvc.ActionNameAttribute>();
    if (attr!=null && attr.Name == expectedActionName)
    {        
       return true;
    }
}

私がコメントで言ったように、私はあなたがあなたの電話で間違っ たことを拾っていると思うので、私は明示的でした.ActionNameAttributetypeof

于 2013-06-07T13:28:00.320 に答える