编辑:由于您需要从 MVC 应用程序中了解 SpecFlow 中的随机值,因此您不需要“模拟”,而是需要一个存根(以及一些小巫术)。
在 ASP.NET MVC 中存根一个随机值,以便 SpecFlow 可以使用它
- 创建一个您的随机值生成器将实现的接口
- 在您的 MVC 项目中创建另一个实现此接口的类,但返回您的 SpecFlow 测试可以使用的已知值
- 在您的 MVC 应用程序的
App.config 文件中添加一个 <appSetting>,以便您指定返回此随机值的具体类
- 在您的 MVC 应用程序中创建一个工厂类,该类读取配置设置并返回一个实现您的随机值接口的对象:
下面的接口和类只是供您学习的示例。我假设您正在生成一个随机的int,但可以使用以下解决方案作为模板来解决您的问题。
创建界面
这个简单的接口只有一个返回int 的方法。没有别的了。
public interface IRandomValueGenerator
{
int GenerateRandomValue();
}
创建实现接口的类
您需要创建返回已知值的“存根”类,并确保您现有的类实现了该接口。
首先,为了测试目的返回一致值的假随机数生成器:
public class FakeRandomValueGenerator : IRandomValueGenerator
{
public int GenerateRandomValue()
{
return 5;
}
}
现在,确保你的真实类实现了这个接口:
public class RealRandomValueGenerator : IRandomValueGenerator
{
public int GenerateRandomValue()
{
return new System.Random().Next();
}
}
将设置添加到 App.config
接下来,您想让随机值生成器可配置,以便在生产中使用真正的生成器,但在集成测试环境中使用存根:
应用程序配置
<appSettings>
<!--
Values:
- random (for deployed sites)
- fake (for the integration testing environment)
-->
<add key="randomValueGenerator" value="fake" />
创建工厂类以返回值生成器
最后一步是创建一个工厂类,它读取您的配置并为IRandomValueGenerator 接口返回一个具体类型。
public static class RandomValueGeneratorFactory
{
public static IRandomValueGenerator GetGenerator()
{
string type = System.Configuration.ConfigurationManager.AppSettings["randomValueGenerator"];
IRandomValueGenerator valueGenerator;
switch (type)
{
case "random":
valueGenerator = new RealRandomValueGenerator();
break;
case "fake":
valueGenerator = new FakeRandomValueGenerator();
break;
default:
throw new System.Configuration.ConfigurationException("Unsupported value for randomValueGenerator: " + type);
}
return valueGenerator;
}
}
拼凑起来
现在您需要更改您的 MVC 应用程序代码以使用工厂:
public class FooController : Controller
{
public ActionResult Create()
{
IRandomValueGenerator generator = RandomValueGeneratorFactory.GetGenerator();
int value = generator.GenerateRandomValue();
// Do other stuff
return View(...);
}
}
依赖注入
您提到依赖注入将是一个很好的解决方案。通过声明一个用于生成随机数的接口,您可以为依赖注入进行设置——但我将其作为练习留给您!