【问题标题】:MsTests : Running selective unit tests with specific DataRow ValueMsTests :使用特定 DataRow 值运行选择性单元测试
【发布时间】:2018-11-03 10:51:14
【问题描述】:

这是我的测试示例(我所有环境的集成测试):

[DataTestMethod]
[DataRow("DEV")]
[DataRow("STAGING")]
[DataRow("PREPROD")]
[DataRow("PROD")]
public void TestMyWebservice(string environnement)
{

}

有什么方法可以执行测试,例如只有 DataRow 值)“STAGING”等。所以我可以一次针对一个环境运行测试。

还有另一种解决方案是复制所有测试并给出一个类别和运行测试,并在所需类别中进行过滤,如下所示:

[TestCategory("DEV")]
[DataTestMethod]
[DataRow("DEV")]
public void TestMyWebservice(string environnement)
{

}

[TestCategory("STAGING")]
[DataTestMethod]
[DataRow("STAGING")]
public void TestMyWebservice(string environnement)
{

}

和过滤命令:

dotnet 测试 --filter TestCategory=DEV

但我真的不喜欢它,因为重复和在某些环境中忘记一些测试的风险

有什么想法吗? 谢谢

【问题讨论】:

    标签: unit-testing continuous-integration tdd integration-testing xunit


    【解决方案1】:

    我会先尝试使用.runsettings 方法来定义运行测试的环境变量:https://docs.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2019#specify-environment-variables-in-the-runsettings-file

    所以理论上,您的不同环境会有不同的文件:

    • dev.runsettings
    • staging.runsettings
    • preprod.runsettings
    • prod.runsettings

    ...可能看起来像这样(请参阅此答案:https://stackoverflow.com/a/65667284/13864681):

    <?xml version="1.0" encoding="utf-8"?>
    <RunSettings>
        <RunConfiguration>
            <EnvironmentVariables>
                <ENV>DEV</ENV>
            </EnvironmentVariables>
        </RunConfiguration>
    </RunSettings>
    

    然后,根据您在代码中设置环境的方式,您可以在测试项目的 [AssemblyInitialize] 方法中执行类似的操作:

    [TestClass]
    public class Config
    {
        // this method will run before any TestMethod in your project
        // and can be used to define project-wide configurations
        [AssemblyInitialize]
        public static void AssemblyInit(TestContext context)
        {
            var env = Environment.GetEnvironmentVariable("ENV");
            // ... use 'env' to set your environment settings
        }
    }
    

    然后,您可以正常定义您的测试,而无需指定它们的环境。

    最后,从命令行运行:

    dotnet test --settings dev.runsettings
    dotnet test --settings staging.runsettings
    dotnet test --settings preprod.runsettings
    dotnet test --settings prod.runsettings
    

    【讨论】:

      猜你喜欢
      • 2010-12-05
      • 2016-08-19
      • 2012-11-25
      • 2013-06-02
      • 2011-07-13
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多