Xunit - 参数化测试 - 类属性 - C# [英] Xunit - Parameterized Tests - Class Properties - C#

查看:28
本文介绍了Xunit - 参数化测试 - 类属性 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Xunit 运行一些 Selenium 测试.我想参数化一些测试,但有一些困难.

I'm using Xunit to run some Selenium tests. I want to parametrize some tests but having some difficulties.

我有一个类,其中包含存储为属性IssuesLogUtils"的元素定位器

I have a class that has the locaters for elements stored as properties "IssuesLogUtils"

public class IssuesLogUtils
{
    // Page Heading
    public By page_heading { get; set; } = By.Id("ctl00_lblPageTitle");

    public By issue_title { get; set; } = By.Id("ctl00_ContentPlaceHolder1_txtNonComplianceName");

然后我在另一个 TestClass 文件中进行 Xunit 测试.我只想在我的测试中使用 IssuesLogUtils 中的属性作为参数.

I then have my Xunit tests in another TestClass file. I want to just use the properties from IssuesLogUtils as params in my tests.

例如

 [Theory]
    [InlineData(issues_log_utils.ifco_radial)]
    [InlineData(issues_log_utils.issue_title)]

我在网上找到了一些文章,它们指出了执行此操作的真正复杂的方法.有什么直接的方法吗?我不想创建一个参数列表,然后传入该列表.

I have found some articles online that point at really convoluted ways of doing this. Is there any straight forward way? I don't want to have to create a list of params which then the list gets passed in.

推荐答案

但 Xunit 不允许我使用属性作为参数

But Xunit won't let me use a property as a param

这不是 XUnit 的错误.InlineData 属性值必须是已知的";在编译时,类似于常量.
某些类实例的属性是运行时值,不能用于常量或属性值.

This is not XUnit fault. InlineData attribute values must be "known" at compile time, similar to constants.
Properties of some class instances are runtime values and cannot be used for constants or attribute values.

注意,你不需要创建一个类,你可以使用带有MemberData属性的静态方法,你可以把它放在测试方法旁边,这样你在阅读测试方法时可以很容易地看到它.

Notice that you don't need to create a class you can use static method with MemberData attribute, which you can put beside the test method, so you can easily see it when reading the test method.

public static IEnumerable<object[]> MyIssuesData()
{
    var issues = new IssuesLogUtils();
    yield return new object[] { issues.page_heading  };
    yield return new object[] { issues.issue_title  };
}

[Theory]
[MemberData(nameof(MyIssuesData))]
public void Should_do_nothing(By issue)
{
     var result = DoSomethingWith(issue);

     result.Should().BeEmpty();
}

这篇关于Xunit - 参数化测试 - 类属性 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆