文章目录
安装SpecFlow
菜单栏——工具——扩展和更新
Nuget
开始使用
新建项目
新建feature文件
生成定义
单击 Generate Step Definitions,出现下图
生成AddTestSteps。
生成的代码文件。
using System;
using TechTalk.SpecFlow;
namespace SpecFlowTest
{
[Binding]
public class AddTestSteps
{
[Given(@"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredIntoTheCalculator(int p0)
{
ScenarioContext.Current.Pending();
}
[Given(@"I have also entered (.*) into the calculator")]
public void GivenIHaveAlsoEnteredIntoTheCalculator(int p0)
{
ScenarioContext.Current.Pending();
}
[When(@"I press add")]
public void WhenIPressAdd()
{
ScenarioContext.Current.Pending();
}
[Then(@"the result should be (.*) on the screen")]
public void ThenTheResultShouldBeOnTheScreen(int p0)
{
ScenarioContext.Current.Pending();
}
}
}
修改为以下
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using TechTalk.SpecFlow;
namespace SpecFlowTest
{
[Binding]
public class AddTestSteps
{
private int result;
private Calculator calculator = new Calculator();
[Given(@"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredIntoTheCalculator(int number)
{
calculator.FirstNumber = number;
}
[Given(@"I have also entered (.*) into the calculator")]
public void GivenIHaveAlsoEnteredIntoTheCalculator(int number)
{
calculator.SecondNumber = number;
}
[When(@"I press add")]
public void WhenIPressAdd()
{
result = calculator.Add();
}
[Then(@"the result should be (.*) on the screen")]
public void ThenTheResultShouldBeOnTheScreen(int expectedResult)
{
Assert.AreEqual(expectedResult, result);
}
}
}
namespace SpecFlowTest
{
public class Calculator
{
public int FirstNumber { get; set; }
public int SecondNumber { get; set; }
public int Add()
{
return FirstNumber + SecondNumber;
}
}
}
Specflow使用的默认测试框架是Nunit,而我们创建的项目使用Mstest。通过修改配置文件app.config添加<unitTestProvider name=“mstest”/>结点来更换。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
</configSections>
<specFlow>
<!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
<unitTestProvider name="mstest"/>
</specFlow>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
运行结果