Home | History | Annotate | Download | only in rules
      1 /*
      2  * Copyright (C) 2016 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 android.icu.cts.coverage.rules;
     17 
     18 import android.icu.util.ULocale;
     19 import org.junit.rules.MethodRule;
     20 import org.junit.runners.model.FrameworkMethod;
     21 import org.junit.runners.model.Statement;
     22 
     23 /**
     24  * Add this as a rule to a JUnit 4 class to support switching the {@link ULocale#getDefault()} for
     25  * the duration of the test method.
     26  *
     27  * <p>Only affects test methods that are annotated with {@link ULocaleDefault}.
     28  *
     29  * @see ULocaleDefault
     30  */
     31 @SuppressWarnings("deprecation")
     32 public class ULocaleDefaultRule implements MethodRule {
     33 
     34     @Override
     35     public Statement apply(final Statement base, FrameworkMethod method, Object target) {
     36         final ULocaleDefault annotation = method.getAnnotation(ULocaleDefault.class);
     37         if (annotation == null) {
     38             return base;
     39         } else {
     40             return new Statement() {
     41                 @Override
     42                 public void evaluate() throws Throwable {
     43                     ULocale previousDefault = ULocale.getDefault();
     44                     try {
     45                         ULocale.setDefault(ULocale.forLanguageTag(annotation.languageTag()));
     46                         base.evaluate();
     47                     } finally {
     48                         ULocale.setDefault(previousDefault);
     49                     }
     50                 }
     51             };
     52         }
     53     }
     54 }
     55