Has anyone had success using NCrunch testing with the long running Hosting.IHostedService Background tasks in .NET Core 2.2?
I have a .NET Core 2.2 web application that has a hosted service (only one) to run tasks during the lifetime of the web application.
The two problems that I'm seeing (which are related) are
[list=1]
In Visual Studio (2019), NCrunch starts a new background task with each integration test run and the background task never exits when the test is finished.
When the TeamCity environment runs the NCrunch integration tests, they never finish and the build step never completes.
I was going to try to use the code below, from the documentation, but it wasn't working for me.
if (Environment.GetEnvironmentVariable("NCrunch") == "1")
{
Console.WriteLine("Running under NCrunch");
}
else
{
Console.WriteLine("Running under something else");
}
Any suggestions would be greatly appreciated.
Thanks!
Alan Visual Studio 2019 version 16.3.4
NCrunch 3.31.0.3
ReSharper Ultimate 2019.2.2
NDepend 2019.2.7
I don't have any personal experience with IHostedService, but perhaps I can provide some general advice.
If the NCrunch environment variable isn't working, something else you can try is to use the compiler constant instead, for example:
#if NCRUNCH
Console.WriteLine("Running under NCrunch");
#else
Console.WriteLine("Running under something else");
#endif
For a test to be able to be reliably executed by NCrunch (or actually, any test runner at all), it must have full control over the lifespan of any background code it executes. This concept applies to both background threads and background processes or services. In your situation, it's critical to be able to establish a handle on the service thread that has been launched by your code so that your test can make an informed decision about how long it should execute for.
Generally, for reliability, you would probably want to arrange your abstractions so that the code responsible for launching any background thread is directly under the control of your test, or perhaps the background code isn't called on a separate thread and is simply called directly. Reliable testing of multi-threaded code is difficult to do and can often result in the creation of flakey tests.
NCrunch itself has no real knowledge of your usage of IHostedService. It just calls your code and expects the test to generally behave itself. If you're experiencing different behaviour inside TeamCity compared with your IDE, it may be worth adding some kind of trace logic to determine the source of the hang-up. You might also be able to surface the same behaviour in your IDE by using NCrunch's churn mode.