场景背景 - 启动wcf服务

时间:2012-11-12 13:47:40

标签: c# specflow topshelf

我正在使用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最佳实践?

1 个答案:

答案 0 :(得分:1)

让我们考虑你想要测试的内容。

  • 您是否需要测试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();
}
相关问题