首页 > 解决方案 > 如何在 nunit 测试用例中使用 Author 属性

问题描述

我想访问 Nunit Author 属性并在 setup 方法中获取作者值。请让我知道正确的做法。

以下是我尝试访问“作者”属性的方式,但得到空值作为回报。它给了我异常对象引用未设置为对象实例。

[TestFixture]
    public class EPTestFlow : MerlinBase
    {

        [Test]
        [Property(PropertyNames.Author,"Kalyani")]
        [TestCaseSource(typeof(TestDataMerlin), "LoginDetails", new object[] { new string[] { "TC01"} })]
        public void PatientEnrollment(string userDetails, LoginDetails loginDetails)
        {

        }
     }

        [SetUp]
        public void TestInitialize()
        {
           var testAuthor = TestContext.CurrentContext.Test.Properties[PropertyNames.Author];
            string name = testAuthor.ToString();
        }

更新了建议的方法:

        [Test]
        [Author("Kalyani")]
        [TestCaseSource(typeof(TestDataMerlin), "LoginDetails", new object[] { new string[] { "TC01"} })]
        public void PatientEnrollment(string userDetails, LoginDetails loginDetails)
        {
        }
[TearDown]
        public void TestCleanup()
        {
            //IList testAuthor = (IList)TestContext.CurrentContext.Test.Properties["Author"];
            //foreach (string author in testAuthor)
            //{
            //    string name12 = author.ToString();
            //}
            //string name = testAuthor.ToString();

            var category = (string)TestContext.CurrentContext.Test.Properties.Get("Author");
}

标签: c#seleniumselenium-webdrivernunit-3.0

解决方案


您将获得“PropertyNames.Author”的空值,因为您在设置之前尝试访问 Author 属性。

由于 SetUp 在每个 Test 方法之前执行,因此在 SetUp 方法中 Author 的值为 null。您可以在“TearDown”方法中获取作者值并在日志中使用它(假设您尝试将作者值用于某些日志记录)。

您可以在此处阅读有关 Nunit 属性的更多信息

尝试在测试方法中设置作者属性,如下所示

 [Test]
 [Author("Author_Name")]
 public void TestTest() { /* ... */ }
}

并在 TearDown 方法中使用以下检索

var category = (string) TestContext.CurrentContext.Test.Properties.Get("Author");

如果您使用的是 TestCaseSource 属性,则使用以下内容在 Test 方法中设置 Author 属性

        [Test]        
        [TestCaseSource(typeof(TestDataMerlin), "LoginDetails", new object[] { new string[] { "TC01"} })]
        public void PatientEnrollment(string userDetails, LoginDetails loginDetails)
        {                      
        TestExecutionContext.CurrentContext.CurrentTest.Properties.Add("Author", "Author_Name");
        }

        [TearDown]
        public void TestCleanup()
        {
            string name = TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Author").ToString();
        }

推荐阅读