【问题标题】:Use nunit custom action attribute with Setup method将 nunit 自定义操作属性与 Setup 方法一起使用
【发布时间】:2014-07-23 15:33:19
【问题描述】:

我已阅读nunit documentation on actions attributes,我想创建一个可用于测试方法或设置方法的操作属性(以避免在所有测试方法上重复该属性)。

我创建了以下类(与文档中的非常相似,但我尝试允许一切):

    [AttributeUsage(
    AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Assembly, 
    AllowMultiple = true)]
public class CustomActionAttribute : Attribute, ITestAction
{
    private string message;

    public CustomActionAttribute(string message) 
    { 
        this.message = message;
    }


    public void BeforeTest(TestDetails details)
    {
        WriteToConsole("Before", details);
    }


    public void AfterTest(TestDetails details)
    {
        WriteToConsole("After", details);
    }


    public ActionTargets Targets
    {
        get { return ActionTargets.Default | ActionTargets.Suite | ActionTargets.Test; }
    }


    private void WriteToConsole(string eventMessage, TestDetails details)
    {
        Console.WriteLine(
            "{0} {1}: {2}, from {3}.{4}.",
            eventMessage,
            details.IsSuite ? "Suite" : "Case",
            message,
            details.Fixture != null ? details.Fixture.GetType().Name : "{no fixture}",
            details.Method != null ? details.Method.Name : "{no method}");
    }
}

什么有效:

    [Test, CustomAction("TEST")]
    public void BasicAssert()
    {
    }

在 nunit Test Runner Text 输出面板中,我有

***** Test.CustomerT.BasicAssert
内部设置
前案例:TEST,来自 CustomerT.BasicAssert。
案例之后:TEST,来自 CustomerT.BasicAssert。

什么不起作用:

    [SetUp, CustomAction("SETUP")]
    public void CustomAttributeBeforeSetup()
    {
        System.Diagnostics.Debug.WriteLine("Inside Setup");
    }


    [Test]
    public void BasicAssert()
    {
    }

在 nunit Test Runner Text 输出面板中,我有

***** Test.CustomerT.BasicAssert
内部设置

?

如何创建可以在 Setup 方法上执行的自定义属性?

【问题讨论】:

    标签: c# nunit custom-attributes


    【解决方案1】:

    我假设您真正想要的是在整个测试夹具之前和之后运行 BeforeTest 和 AfterTest。如果是这种情况,那么不要将其放在 SetUp 方法上,而是将属性放在 Fixture 上,即测试类。在 TestDetails 中,您可以通过检查 TestDetails.IsSuite 来查看特定方法(即 BeforeTest 和 AfterTest)是否针对测试或夹具运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      相关资源
      最近更新 更多