9

testdelegateまたはdelegateを受け取り、パラメーターをdelegateオブジェクトに渡すメソッドを作成しようとしています。これは、すべてが同じパラメーター(ID)をとるコントローラーのメソッドのテストを作成しており、すべてのコントローラーメソッドのテストを作成したくないためです。

私が持っているコード:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod)
{

    Assert.Throws<NullReferenceException>(delegateMethod);
    Assert.Throws<InvalidOperationException>(delegateMethod);
    Assert.Throws<InvalidOperationException>(delegateMethod);
} 

私がしたいこと:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod)
{

    Assert.Throws<NullReferenceException>(delegateMethod(null));
    Assert.Throws<InvalidOperationException>(delegateMethod(string.Empty));
    Assert.Throws<InvalidOperationException>(delegateMethod(" "));
} 

編集:コントローラーに戻り値があることを忘れました。したがって、アクションは使用できません。

4

2 に答える 2

14

Action<string>単一の文字列パラメータを受け入れるメソッドを渡すために使用します。テストパラメータを使用してそのアクションを呼び出します。

protected void AssertThrowsNullReferenceOrInvalidOperation(Action<string> action)
{
    Assert.Throws<NullReferenceException>(() => action(null));
    Assert.Throws<InvalidOperationException>(() => action(String.Empty));
    Assert.Throws<InvalidOperationException>(() => action(" "));
}

使用法:

[Test]
public void Test1()
{
    var controller = new FooController();
    AssertThrowsNullReferenceOrInvalidOperation(controller.ActionName);
}

アップデート:

Func<string, ActionResult>ActionResultを返すコントローラーに使用します。また、その目的のためにジェネリックメソッドを作成することもできます。

于 2013-01-02T09:51:46.747 に答える
2

編集で述べたように、コントローラーにはリターンタイプがあります。そのため、ActionからFuncに変更する必要があり、単体テストで使用したため、関数を保持する一時オブジェクトを作成する必要がありました。

lazyberezovskyの答えに基づいて、ここに私の結果のコードがあります:

    public class BaseClass
    {
            protected Func<string, ActionResult> tempFunction;
            public virtual void AssertThrowsNullReferenceOrInvalidOperation()
            {
                if (tempFunction != null)
                {
                    Assert.Throws<NullReferenceException>(() => tempFunction(null));
                    Assert.Throws<InvalidOperationException>(() => tempFunction(string.Empty));
                    Assert.Throws<InvalidOperationException>(() => tempFunction(" "));
                }
            }
    }

単体テストは次のとおりです。

[TestFixture]
public class TestClass
{
        [Test]
        public override void AssertThrowsNullReferenceOrInvalidOperation()
        {
            tempFunction = Controller.TestMethod;
            base.AssertThrowsNullReferenceOrInvalidOperation();
        }
}
于 2013-01-02T11:19:27.203 に答える