我正在使用 specflow 和 nunit 测试 WCF 服务方法;我的场景如下所示:
Feature: GetAccount
Testing API method 'get account'
Background:
Given Server is running
Scenario: Succesful Get
Given An Existing Account
When I call the GetAccount API method With password = "123"
Then the result should be Success
我不确定如何实现后台步骤;
服务器可以使用 Topshelf- 作为控制台/Windows 服务运行-
private static void Main()
{
Host host = HostFactory.New(config =>
{
config.Service<ServiceInitializer>(service =>
{
service.ConstructUsing(s => new ServiceInitializer());
service.WhenStarted((s, control) => s.Start(control));
service.WhenStopped((s, control) => s.Stop(control));
});
config.RunAsPrompt();
});
host.Run();
}
public class ServiceInitializer : ServiceControl
{
private readonly ILog m_log;
public ServiceInitializer()
{
log4net.Config.XmlConfigurator.Configure();
m_log = LogManager.GetLogger("Server");
}
public bool Start(HostControl hostControl)
{
try
{
var host = new IoCServiceHost(typeof(MyService));
host.Open();
m_log.Info("Server is now open.");
return true;
}
catch (Exception exception)
{
m_log.Fatal("Initialization of service failed",exception);
return false;
}
}
public bool Stop(HostControl hostControl)
{
m_log.Info("Server has closed");
return true;
}
}
我应该只执行 .exe 服务文件,还是可以以某种方式使用我的 ServiceInitializer
?也许我可以使用 nUnit 的 [SetUpFixture]
?
是否有任何 Specflow 最佳实践?
最佳答案
让我们考虑一下您要测试的内容。
- 您是否需要测试 Windows 是否正确运行服务?
- 您是否需要测试 Topshelf 是否正确启动服务?
- 或者您只是想测试 GetAccount 是否有效?
我敢打赌,您使用 Topshelf 是为了让您的生活更轻松,所以这样做并相信他们的代码可以在 Windows 中运行。这是一个有效的假设,因为那里的代码将在许多地方使用,并且他们可能有自己的测试套件,如果您的假设是错误的,请稍后在发现问题时进行测试。
所以你真正需要的是
[BeforeFeature]
public void Background()
{
FeatureContext.Current["Host"] =new MyHostObject();
}
[When("I call GetAccount API method with password =\"(\.*)\"")]
public void WhenICallGetAccount(string password)
{
var host = (MyHostObject)FeatureContext.Current["Host"];
ScenarioContext.Current["Account"] = host.GetAccount(password);
}
[Then("the result should be success")]
public void ThenTheResultShouldBeSuccessful()
{
var account = (MyAccount)ScenarioContext.Current["Account"];
//assuming using Should;
account.ShouldNotBeNull();
}
关于c# - 场景背景-启动wcf服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344878/