有没有办法在一个单元测试中设置一个可以被另一个单元测试使用的值

Woj*_*icz 2 c# unit-testing

我有一个简单的问题,我创建了一个单元测试类,可以说它看起来像这样:

namespace Tests
{
    [TestClass]
    public class ApiTest
    {
         private var x;

         [TestMethod]
         public testA()
         {
             some operactons
             x = some value
         }

         [TestMethod]
         public testB()
         {
             if(x == null)
                test fail
         }
    }
Run Code Online (Sandbox Code Playgroud)

现在如上所述,我感兴趣的是,是否可以在测试方法 A 中设置一个值 (x) 以便它可以用于测试方法 B?

Mar*_*l B 5

您可以通过将 var x 声明为静态来做到这一点:

private static var x;
Run Code Online (Sandbox Code Playgroud)

但我不建议从 TestMethod 设置变量。如果“var x”是您在所有其他测试方法(testC、testD 等)中都需要的变量,则在 ClassInitialize() 中设置它。这样 var x 可用于类 ApiTest 中的每个 TestMethod。

[TestClass]
public class ApiTest
{
     private static var x;

     [ClassInitialize()]
     public static void InitApiTest(TestContext context)
     {
         some operactons
         x = some value
     }

     [TestMethod]
     public testA()
     {
         //Obsolete
     }

     [TestMethod]
     public testB()
     {
         if(x == null)
            test fail
         else
            ...
     }
}
Run Code Online (Sandbox Code Playgroud)