问题
I previously asked how to fail a unit test from a thread pool.
@Test
public void foo() throws Exception {
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
stpe.submit(new Runnable() {
@Override
public void run() {
// does not make this unit test fail :(
Assert.AssertEquals(1, 2);
}
});
}
The solution I accepted was to block on the returned Future
and get. But in my actual setting I own neither the threadpool nor the submit call - it's a callback that ultimately originates from MINA.
About the best idea I have is messing around with the global default exception handler but seems very kludgy.
Maven surefire if it matters.
回答1:
I meet the same question, and my question is here: TestNG Make assert in multithread way (not run in multithread)
and here's my solution:
As java pass method's parameter by reference, so I wrote a ResultWrapper class
public class ResultWrapper {
boolean result;
public boolean getResult()
{
return result;
}
public void setResult(boolean result)
{
this.result = result;
}
}
Instead of making any assert in public void run()
I put the result into ResultWrapper: resultWrapper.setResult(actual == expectedAssert);
(the ResultWrapper is pass to the class which call the Runnable class in Constructor)
And I make assert outSide in test method like this:
@Test
public void assign_assign_release_release() throws ClientProtocolException, IOException, InterruptedException{
assignUntilSuccess();
releaseUntilSuccessAndExpect(1);
Assert.assertTrue(resultWrapper.getResult());
}
Hope this would be helpful.
来源:https://stackoverflow.com/questions/15170055/failing-testng-unit-test-from-a-callback-i-dont-own-in-my-code