1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.compatibility.common.util;
17 
18 import org.junit.rules.TestRule;
19 import org.junit.runner.Description;
20 import org.junit.runners.model.Statement;
21 
22 /**
23  * Custom JUnit4 rule that provides "before" / "after" callbacks, which is useful to use with
24  * {@link org.junit.rules.RuleChain}.
25  */
26 public class BeforeAfterRule implements TestRule {
27     @Override
apply(Statement base, Description description)28     public Statement apply(Statement base, Description description) {
29         return new Statement() {
30 
31             @Override
32             public void evaluate() throws Throwable {
33                 onBefore(base, description);
34                 try {
35                     base.evaluate();
36                 } finally {
37                     onAfter(base, description);
38                 }
39             }
40         };
41     }
42 
43     protected void onBefore(Statement base, Description description) throws Throwable {
44     }
45 
46     protected void onAfter(Statement base, Description description) throws Throwable {
47     }
48 }
49