如何在 nunit 测试用例中使用 Author 属性

how to use Author attribute in nunit test cases

我想访问 Nunit 作者属性并在设置方法中获取作者值。 请告诉我正确的做法。

以下是我尝试访问 "Author" 属性但在 return 中得到空值的方式。 它给我异常 Object reference not set to instance of object.

[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");
}

您正在获得 'PropertyNames.Author' 的空值,因为您试图在设置之前访问作者 属性。

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

您可以阅读有关 Nunit 属性的更多信息here

尝试在测试方法中像下面这样设置作者属性

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

并在 TearDown 方法中使用下面的方法进行检索

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

如果您使用的是 TestCaseSource 属性,则使用以下设置测试方法中的作者 属性

        [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();
        }