gpt4 book ai didi

c# - 使用 Topshelf 进行集成测试以启动 C# Windows 服务

转载 作者:太空狗 更新时间:2023-10-29 21:54:57 29 4
gpt4 key购买 nike

我正在使用 Topshelf托管用 C# 编写的 Windows 服务,我现在想编写一些集成测试。我的初始化代码保存在如下启动器类中:

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

我想编写一些集成测试以确保正确设置 log4net 和 Ninject 以及 Topshelf 启动我的服务。问题是,一旦您在 Topshelf 主机上调用 Run(),代码就会阻塞,因此我的测试代码永远不会运行。

我想在测试的 SetUp 部分的单独线程中调用 Launch(),但我需要一些 hack 来放入 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 中的显式配置和易于安装。

最佳答案

https://github.com/Topshelf/Topshelf/blob/v2.3/src/Topshelf/Config/Builders/RunBuilder.cs#L113我想这就是你想要的。 AfterStartingService 可用于从不同线程设置 ManualResetEvent

现在这可能适合您,但这感觉过于复杂并且可以通过部署到开发/暂存并对您的系统进行冒烟测试来验证。但是,如果不更多地了解您的环境,这可能是不可能的。

关于c# - 使用 Topshelf 进行集成测试以启动 C# Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11742281/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com