ExternalResource vs @ Before / @ After

时间:2012-09-02 16:29:23

标签: java junit

我正在尝试使用JUnit规则:ExternalResource并且没有看到针对@Before和@After的区别。

@Rule
public ExternalResource externalResource = new ExternalResource() {

    @Override
    protected void before() throws Throwable {
        super.before();
        LOG.info("before");
        serverSocket = new ServerSocket(2004, 10);
        socket = new Socket();
        socket.connect(serverSocket.getLocalSocketAddress());
    }

    @Override
    protected void after() {
        super.after();
        LOG.info("after");
        try {
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            LOG.log(Level.SEVERE , "Error closing socket", e);
        }
    }
};

此代码的安全性为:

1. before (ExternalResource)
2. before (@Before)
3. after  (@After)
4. after  (ExternalResource)

使用ExternalResource有什么好处?

1 个答案:

答案 0 :(得分:4)

您可以比在方法之前/之后共享更轻松地在多个测试类中重用ExternalResource实现。