• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.base.test.util;
6 
7 import android.text.TextUtils;
8 
9 import org.hamcrest.Description;
10 import org.hamcrest.Matcher;
11 import org.hamcrest.StringDescription;
12 
13 /**
14  * Provides a means for validating whether some condition/criteria has been met.
15  * <p>
16  * See {@link CriteriaHelper} for usage guidelines.
17  */
18 public final class Criteria {
Criteria()19     private Criteria() {}
20 
21     /**
22      * Validates that a expected condition has been met, and throws an
23      * {@link CriteriaNotSatisfiedException} if not.
24      *
25      * @param <T> The type of value whose being tested.
26      * @param actual The actual value being tested.
27      * @param matcher Determines if the current value matches the desired expectation.
28      */
checkThat(T actual, Matcher<T> matcher)29     public static <T> void checkThat(T actual, Matcher<T> matcher) {
30         checkThat("", actual, matcher);
31     }
32 
33     /**
34      * Validates that a expected condition has been met, and throws an
35      * {@link CriteriaNotSatisfiedException} if not.
36      *
37      * @param <T> The type of value whose being tested.
38      * @param reason Additional reason description for the failure.
39      * @param actual The actual value being tested.
40      * @param matcher Determines if the current value matches the desired expectation.
41      */
checkThat(String reason, T actual, Matcher<T> matcher)42     public static <T> void checkThat(String reason, T actual, Matcher<T> matcher) {
43         if (matcher.matches(actual)) return;
44         Description description = new StringDescription();
45         if (!TextUtils.isEmpty(reason)) {
46             description.appendText(reason).appendText(System.lineSeparator());
47         }
48         description
49                 .appendText("Expected: ")
50                 .appendDescriptionOf(matcher)
51                 .appendText(System.lineSeparator())
52                 .appendText("     but: ");
53         matcher.describeMismatch(actual, description);
54         throw new CriteriaNotSatisfiedException(description.toString());
55     }
56 }
57