I have a multi-threaded class which throws an exception in a child thread:
public class TestClass
{
private Thread theThread;
private string failString = string.Empty;
private CancellationTokenSource cancelToken;
public void OnStart()
{
cancelToken = new CancellationTokenSource();
theThread = new Thread(() => ThreadOperation(cancelToken.Token));
theThread.Start();
}
private void ThreadOperation(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
if(failString[0] == ',')
{
Console.WriteLine("Foo");
}
Thread.Sleep(10);
}
}
public void OnStop()
{
cancelToken.Cancel();
theThread.Join();
}
}
And I want to write a unit test that catches the exception and fails in that case. But a simple unit test trying to catch the exception fails only in Debug:
[TestMethod]
public void TestException()
{
TestClass testClass = new TestClass();
testClass.OnStart();
Thread.Sleep(1000);
testClass.OnStop();
}
If I just run this test (without debugging), it passes successfully (which is not the behavior I want to achieve).
I've tried this but it doesn't fail either:
[TestMethod]
public void TestException()
{
try
{
TestClass testClass = new TestClass();
testClass.OnStart();
Thread.Sleep(1000);
testClass.OnStop();
}
catch(Exception)
{
Assert.Fail();
}
}
Is there any way to catch the exceptions of all threads (including children) and make the test fail in that case without rewriting the original class?