当我们使用MSTest时,我们有几个环境有自己的运行设置。由于微软正在放弃MSTest,我们将改用xUnit。无论是通过runsettings还是命令行属性,我都需要一种在xUnit测试中指定TestRunParameters的方法。xUnit是否有像MSTest一样的本地方法来实现这一点,或者我是否需要提出自己的解决方案?
虽然在使用xUnit时仍然可以使用RunSettings来控制vstest.console的某些方面,但当前版本没有传入参数的本地方式。我相信v3会有一些参数传递。
目前,您可以使用环境变量,但如果在同一系统上并行运行多个测试集,则会发生冲突。
我使用一个基类,它读取带有该测试集设置的TestSettings.json文件。使用以下代码,我可以传入新类型,并让基类json读取器读取它们。
/// <inheritdoc />
/// <summary>
/// Common TestBase which uses CommonSettingsModel. Use TestBase<T> to override with custom settings Type.
/// </summary>
public abstract class TestBase : TestBase<CommonSettingsModel>
{
}
/// <inheritdoc />
/// <summary>
/// Common TestBase for loading settings.
/// </summary>
/// <typeparam name="T">Type to read TestSettings.json file</typeparam>
public abstract class TestBase<T> where T : ICommonSettings, new()
{
/// <inheritdoc />
/// <summary>
/// Constructor loads Settings T
/// </summary>
protected TestBase()
{
Settings = SettingsUtil.GetSettings<T>();
}
/// <summary>
/// Settings T loaded from TestSettings.json
/// </summary>
protected T Settings { get; }
}
您也可以对类或AssemblyFixture进行相同类型的测试。
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
DatabaseFixture fixture;
public MyDatabaseTests(DatabaseFixture fixture)
{
this.fixture = fixture;
}
// ... write tests, using fixture.Db to get access to the SQL Server ...
}
- https://xunit.net/docs/shared-context