我正在尝试 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 有什么好处?