Failing TestNG unit test from a callback I don't own in my code

折月煮酒 提交于 2019-12-13 18:26:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!