2012-11-12 111 views
2

我使用specflow和nunit测试WCF服务方法;我的方案如下所示:场景背景 - 启动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-

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文件服务控制台/ Windows服务,或者我可以用我的ServiceInitializer以某种方式?也许我可以使用nUnit的[SetUpFixture]? 有没有Specflow最佳实践?

回答

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(); 
}