1 /* 2 * Copyright (C) 2017 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 17 package com.android.settings.testutils; 18 19 import static com.google.common.truth.Truth.assertAbout; 20 21 import static org.robolectric.RuntimeEnvironment.application; 22 23 import android.support.annotation.Nullable; 24 25 import com.google.common.truth.ComparableSubject; 26 import com.google.common.truth.FailureStrategy; 27 import com.google.common.truth.SubjectFactory; 28 29 /** 30 * Custom subject for use with {@link com.google.common.truth.Truth}, to provide a more readable 31 * error message, so that instead of "Not true that 2130706432 equals to 17170444", it will say 32 * "Not true that color/my_color equals to android:color/black". 33 * 34 * <p>Usage: 35 * <pre>{@code 36 * ResIdSubject.assertResId(activity.getThemeResId()).isEqualTo(android.R.style.Theme_Material) 37 * }</pre> 38 */ 39 public class ResIdSubject extends ComparableSubject<ResIdSubject, Integer> { 40 41 public static final SubjectFactory<ResIdSubject, Integer> FACTORY = 42 new SubjectFactory<ResIdSubject, Integer>() { 43 @Override 44 public ResIdSubject getSubject( 45 FailureStrategy failureStrategy, Integer integer) { 46 return new ResIdSubject(failureStrategy, integer); 47 } 48 }; 49 assertResId(int resId)50 public static ResIdSubject assertResId(int resId) { 51 return assertAbout(ResIdSubject.FACTORY).that(resId); 52 } 53 ResIdSubject( FailureStrategy failureStrategy, @Nullable Integer integer)54 public ResIdSubject( 55 FailureStrategy failureStrategy, 56 @Nullable Integer integer) { 57 super(failureStrategy, integer); 58 } 59 isEqualTo(int other)60 public void isEqualTo(int other) { 61 Integer subject = getSubject(); 62 if (subject == null || subject != other) { 63 fail("equals to", resIdToString(other)); 64 } 65 } 66 67 @Override getDisplaySubject()68 protected String getDisplaySubject() { 69 String resourceName = "<" + resIdToString(getSubject()) + ">"; 70 String customName = internalCustomName(); 71 if (customName != null) { 72 return customName + " " + resourceName; 73 } else { 74 return resourceName; 75 } 76 } 77 resIdToString(int resId)78 private static String resIdToString(int resId) { 79 return application.getResources().getResourceName(resId); 80 } 81 } 82