如何在specflow测试中读取测试运行设置参数值?

时间:2017-12-13 10:40:58

标签: mstest specflow testcontext

我们在visual studio中使用.runsettings文件来运行specflow测试。我们配置了某些参数。我需要在运行时访问这些参数值以在specflow测试方法中使用。我尝试通过TestContext访问它们,如下所示

 [ClassInitialize]
    public static void Initialize(TestContext testContext)
        {            
            var value= 
            Convert.ToString(testContext.Properties["testParameter1"]);
        }

我在运行时获得testcontext实例的异常,如下所示。 " System.NullReferenceException:'对象引用未设置为对象的实例。'"

环境 Visual Studio Enterprise 2017 Specflow 2.2.1 单元测试提供者:MsTest

此代码在Microsoft Unit Test项目中使用时工作正常。如何从测试运行设置文件中读取值以进行specflow测试?有没有其他方法可以访问runsettings参数?

1 个答案:

答案 0 :(得分:1)

因为它们在TestContext上,所以你需要它的实例。

你可以通过DI获得它:

#include <stdio.h>

#define TEST1
#define TEST2 0
#define TEST3 1
// define TEST4 // not defined

#define ENABLED(x) (1 - x -1 != 0)

int main(void)
{

#if defined TEST1 && ENABLED(TEST1)
    printf("TEST1 is enabled!\n");
#endif

#if defined TEST2 && ENABLED(TEST2)
    printf("TEST2 is disabled!\n");
#endif

#if defined TEST3 && ENABLED(TEST3)
    printf("TEST3 is enabled!\n");
#endif

#if defined TEST4 && ENABLED(TEST4)
    printf("TEST4 is disabled!\n");
#endif

    return 0;
}

完整示例:https://github.com/techtalk/SpecFlow/blob/master/Tests/TechTalk.SpecFlow.Specs/Features/MsTestProvider.feature#L43

但请注意,它目前不适用于BeforeScenario挂钩(https://github.com/techtalk/SpecFlow/issues/936

相关问题