TestWatcher in junit5

本小妞迷上赌 提交于 2019-11-28 08:02:35

问题


I can't find any annotation which replace/working the same like TestWatcher.

My goal: Have 2 functions which do something depend on test result.

  • Success? Do something
  • Fail? Do something else

回答1:


TestWatcher was introduced to Junit 5.4.0 some days ago:

  • https://github.com/junit-team/junit5/pull/1393
  • https://junit.org/junit5/docs/5.4.0/release-notes/
  • https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html

In order to use it you have to:

  1. Implement TestWatcher class (org.junit.jupiter.api.extension.TestWatcher)
  2. Add @ExtendWith(<Your class>.class) to your tests classes (I personally use a base test class which I extend in every test) (https://junit.org/junit5/docs/current/user-guide/#extensions)

TestWatcher provides you with 4 methods to do something on test abort, failed, success and disabled:

  • testAborted​(ExtensionContext context, Throwable cause)
  • testDisabled​(ExtensionContext context, Optional<String> reason)
  • testFailed​(ExtensionContext context, Throwable cause)
  • testSuccessful​(ExtensionContext context)

https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html

Sample TestWatcher implementation:

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class MyTestWatcher implements TestWatcher {
    @Override
    public void testAborted(ExtensionContext extensionContext, Throwable throwable) {
        // do something
    }

    @Override
    public void testDisabled(ExtensionContext extensionContext, Optional<String> optional) {
        // do something
    }

    @Override
    public void testFailed(ExtensionContext extensionContext, Throwable throwable) {
        // do something
    }

    @Override
    public void testSuccessful(ExtensionContext extensionContext) {
        // do something
    }
}

Then you just put this on your tests:

@ExtendWith(MyTestWatcher.class)
public class TestSomethingSomething {
...


来源:https://stackoverflow.com/questions/49037406/testwatcher-in-junit5

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