Integration tests using Topshelf to start a Windows C # service

I use Topshelf to host a Windows service written in C #, and now I want to write some integration tests. My initialization code is stored in the launch class, for example:

public class Launcher
{
    private Host host;

    /// <summary>
    /// Configure and launch the windows service
    /// </summary>
    public void Launch()
    {
        //Setup log4net from config file
        log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(DEFAULT_CONFIG));

        //Setup Ninject dependency injection
        IKernel kernel = new StandardKernel(new MyModule());

        this.host = HostFactory.New(x =>
        {
            x.SetServiceName("MyService");
            x.SetDisplayName("MyService");
            x.SetDescription("MyService");

            x.RunAsLocalSystem();
            x.StartAutomatically();

            x.Service<MyWinService>(s =>
            {
                s.ConstructUsing(() => kernel.Get<MyWinService>());
                s.WhenStarted(w => w.Start());
                s.WhenStopped(w => w.Stop());
            });
        });

        this.host.Run(); //code blocks here
    }

    /// <summary>
    /// Dispose the service host
    /// </summary>
    public void Dispose()
    {
        if (this.host != null && this.host is IDisposable)
        {
            (this.host as IDisposable).Dispose();
            this.host = null;
        }
    }
}

I want to write some integration tests to make sure log4net and Ninject are configured correctly, and Topshelf starts my service. The problem is that after a call Run()on the Topshelf host, the code simply blocks, so my test code never runs.

Launch() SetUp , , Thread.Sleep(1000), , Launch() . (, ManualResetEvent), Launch() . :

private Launcher launcher;
private Thread launchThread;

[TestFixtureSetUp]
public void SetUp()
{
    launcher = new Launcher();
    launchThread = new Thread(o => launcher.Launch());
    launchThread.Start();
    Thread.Sleep(2500); //yuck!!
}

[TestFixtureTearDown]
public void TearDown()
{
    if (launcher != null)
    {
        launcher.Dispose(); //ouch
    }
}

, , , TearDown. TearDown ( TearDown !).

- Topshelf ? , ServiceHost, Topshelf.

+5
2

https://github.com/Topshelf/Topshelf/blob/v2.3/src/Topshelf/Config/Builders/RunBuilder.cs#L113 , , . AfterStartingService ManualResetEvent .

, dev/staging . , , .

+2

, Topshelf ( Ninject ).

, Run ConsoleRunHost , ManualResetEvent , .

, /, โ€‹โ€‹ SetUp, , TearDown

0

All Articles