我希望能够编写这样的测试:
Background:
Given a user signs up for a 30 day account
Scenario: access before expiry
When they login in 29 days
Then they will be let in
Scenario: access after expiry
When they login in 31 days
Then they will be asked to renew
Scenario: access after acounnt deleted
When they login in 2 years time
Then they will be asked to register for a new account
如何进行测试的规范流方面?
编辑:相同的步骤定义如何同时处理“31 天”和“2 年时间”
最佳答案
构建这个 .feature 文件将为测试创建一个代码。然后,您需要将每个步骤连接到一个方法。最简单的方法是,
1:调试测试,测试将因不确定而失败。查看测试运行结果规范流可以通过为此测试添加模板来帮助您。错误消息看起来像这样
Assert.Inconclusive 失败。没有为一个或多个步骤找到匹配的步骤定义。
[Binding]
public class StepDefinition1
{
[Given(@"a user signs up for a 30 day account")]
public void GivenAUserSignsUpForA30DayAccount()
{
}
[When(@"they login in 29 days")]
public void WhenTheyLoginIn29Days()
{
ScenarioContext.Current.Pending();
}
[Then(@"they will be let in")]
public void ThenTheyWillBeLetIn()
{
ScenarioContext.Current.Pending();
}
}
2:将其复制到一个新的 specflow 步骤定义文件中,该文件基本上只是填充了 specflow 属性的单元测试类。现在有一些技巧可以帮助你。在 GivenAUserSignsUpForA30DayAccount 方法中,我将创建一个用户,该用户将在具有 30 天试用帐户的测试中使用。私有(private)成员在这里可以正常工作,因此您可以在方法之间访问它们,但这仅在所有方法都在同一个类中时才有效。如果您尝试在多个功能/类之间重用方法,则需要考虑将对象保存到 ScenarioContext
3:当 specflow 测试运行时,它会查找具有相同字符串的匹配属性的方法。这里的一个技巧是您可以使用方法属性中的通配符将参数传递给方法。有 2 种不同的文件卡
(.*) 表示您将字符串传递给该方法
(\d+) 表示您将 int 传递给该方法。
因为您的 When 方法很常见,您可以使用这样的参数重用它。
[When(@"they login in (\d+) days")]
public void WhenTheyLoginInDays(int daysRemaining)
{
Account.DaysRemaining = daysRemaining;
}
4:最后将您的 Asserts 添加到 Then 方法中,最终结果看起来像这样。 (请注意,我个人会稍微调整功能的措辞并传递预期的结果,这样测试逻辑并不像我的示例那样令人讨厌,请查看数据驱动测试的场景大纲)
[Binding]
public class StepDefinition1
{
UserAccount user;
[Given(@"a user signs up for a 30 day account")]
public void GivenAUserSignsUpForA30DayAccount()
{
user = AccountController.CreateNewUser("bob", "password", AccountType.Trial);
}
[When(@"they login in (\d+) days")]
public void WhenTheyLoginInDays(int daysRemaining)
{
Account.DaysRemaining = daysRemaining;
}
[Then(@"they will (.*)")]
public void ThenTheyWillBeLetIn(string expected)
{
//check to see which test we are doing and then assert to see the expected result.
if(string.Compare(expected, "be let in", true)
Assert.AreEqual(LoginResult.Passed, LoginService.Login);
if(string.Compare(expected, "be asked to renew", true)
Assert.AreEqual(LoginResult.Passed, LoginService.Login);
}
}
关于.net - 我怎样才能让 specflow 很好地处理日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5187607/