我有一个有两种类型用户的应用程序。说,我们有用户
这是测试的一个例子:
[TestFixture]
public class TestCalls
{
private static RestApiClient client;
[SetUp]
public void Init()
{
client = new RestApiClient("http://localhost:1234/");
SetToken("A", "1234");
}
[Test]
public async Task ExampleTest()
{
// a test methods
var value = await client.ExecuteRequestAsync(...);
Assert.That(value, Is.Not.Null.And.Not.Empty)
// more assertions
}
}
SetToken
只需在我的RestApiClient
- insance上设置身份验证令牌。
问题是用户A获得的值不是用户B(当然是相同类型,不同的值,而是另一个数据库)
我可以使用TestCaseAttribute
来解决这个问题,但我想在SetToken
中使用SetUpAttribute
- 方法Init()
[Test]
[TestCase("A")]
[TestCase("B")]
public async Task ExampleTest(string user)
{
SetToken(user, "1234"); // of course setting right password
// a test methods
var value = await client.ExecuteRequestAsync(...);
Assert.That(value, Is.Not.Null.And.Not.Empty)
// more assertions
}
是否有可能像NUnit那样配置?所以我可以运行两次(对于两个用户)? 或者我可以做些什么来测试这两个用户? (复制粘贴所有测试都不是解决方案)
答案 0 :(得分:1)
找到解决方案:
我们可以添加多个TestFixture
- 属性并为其赋值。
我们需要为具有相同数量参数的测试类定义构造函数。
然后在构造函数中我们将这些值分配给字段(这里我使用的是私有只读字段)
然后我们可以在SetUp
中使用它们。
NUnit会自动为两个用户创建测试用例。
我的Test-class现在看起来像这样:
[TestFixture("A", "1234")]
[TestFixture("B", "ABCD")]
public class TestCalls
{
private static RestApiClient client;
private readonly string username;
private readonly string password;
public TestCalls(string username, string password)
{
this.username = username;
this.password = password;
}
[SetUp]
public void Init()
{
client = new RestApiClient("http://localhost:1234/");
SetToken(this.username, this.password);
}
[Test]
public async Task ExampleTest()
{
// a test methods
var value = await client.ExecuteRequestAsync(...);
Assert.That(value, Is.Not.Null.And.Not.Empty)
// more assertions
}
}