I have unit test sample code that basically runs 2 threads: the main test thread and another thread I’m launching that is supposed to fail the test execution after some time (this is basically a timeout thread)
Code is as follows:
[TestClass]
public class SomeTestClass
{
[TestInitialize]
public void BeforeTest()
{
var task = new Task(abortIfTestStilRunsAfterTimeout);
task.Start();
}
[TestMethod]
public void TestMethod()
{
Thread.Sleep(5000);
}
private void abortIfTestStilRunsAfterTimeout()
{
Assert.Fail("timeout passed!");
}
}
Well, I was expecting that the TestMethod() test should fail but what actually happens is that the task thread that runs the Assert.Fail method gets an exception while the other thread keeps on running and the test passes.
I’m looking for a way to fail the test method
You can try and get a reference to the test thread and call
Abort()on it. You can pass an exception state object toAbort()which you can use to pass a fail message:In case you do not want to modify some 100 tests you can use a tool like PostSharp to modify your test cases by inserting the
try {} catch {}logic around each test case for you. All it boils down to is to write an attribute and decorate you test assembly with it (it’s called Aspect Oriented Programming and the framework in PostSharp for that is called Laos).