Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# xUnit类构造函数应获取从理论测试方法传递的参数_C#_.net_.net Core_Xunit - Fatal编程技术网

C# xUnit类构造函数应获取从理论测试方法传递的参数

C# xUnit类构造函数应获取从理论测试方法传递的参数,c#,.net,.net-core,xunit,C#,.net,.net Core,Xunit,在xUnit网站上,它说了以下关于构造函数的内容: net为每个测试创建一个新的测试类实例 运行,因此放入测试构造函数中的任何代码 类将为每个测试运行。这使得构造函数成为 方便地将可重用上下文设置代码放置在您想要的位置 在不共享对象实例的情况下共享代码(这意味着,您将获得 为每个运行的测试清理上下文对象的副本) 我有以下代码: public class ProfilePageTest { public ProfilePageTest(Role role) { A

在xUnit网站上,它说了以下关于构造函数的内容:

net为每个测试创建一个新的测试类实例 运行,因此放入测试构造函数中的任何代码 类将为每个测试运行。这使得构造函数成为 方便地将可重用上下文设置代码放置在您想要的位置 在不共享对象实例的情况下共享代码(这意味着,您将获得 为每个运行的测试清理上下文对象的副本)

我有以下代码:

public class ProfilePageTest
{
    public ProfilePageTest(Role role) 
    {
        AuthRepository.Login(role)
    }

    [Theory]
    [Roles(Role.Editor, Role.Viewer)]
    public void OpenProfilePageTest(Role role)
    {
        var profile = GetPage<ProfilePage>();
        profile.GoTo();
        profile.IsAt();
    }
}
公共类ProfilePageTest
{
公共配置文件页面测试(角色)
{
AuthRepository.Login(角色)
}
[理论]
[角色(Role.Editor、Role.Viewer)]
public void OpenProfilePageTest(角色)
{
var profile=GetPage();
profile.GoTo();
profile.IsAt();
}
}

是否可以将角色从theory属性传递给构造函数,这样我就不必在我拥有的每个测试方法中都执行AuthRepository.Login(role)。

不,这是不可能的。构造函数将在运行之前运行,就像您使用的任何构造函数一样。不过,我不认为在每个测试中调用
AuthRepository.Login(role)
有什么害处,因为它只是一行代码。

是一篇非常优秀的博客文章,介绍了将数据传递到xUnit测试的不同方法,但它们都是将数据传递到单个方法(测试)而不是构造函数中

如果您希望为多个测试设置一些内容,那么应该查看int

快速运行,您可以使用共享数据设置一个类:

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 ...
}
公共类MyDatabaseTests:IClassFixture
{
数据库夹具;
公共MyDatabaseTests(数据库夹具)
{
这个。夹具=夹具;
}
//…编写测试,使用fixture.Db访问SQL Server。。。
}

不,这是不可能的<代码>登录方法是测试的一部分,在每个测试中编写它将比在一个地方干燥/隐藏它为未来的读者/维护人员提供更多的价值。