1 /* 2 * Copyright (C) 2024 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.adservices.shared.testing; 17 18 import com.google.common.truth.StandardSubjectBuilder; 19 20 import java.util.Objects; 21 22 /** Helper class used to test the implementation of {@code equals()} and {@code hashCode()}. */ 23 public final class EqualsTester { 24 25 private final StandardSubjectBuilder mExpect; 26 27 /** Default constructor. */ EqualsTester(StandardSubjectBuilder expect)28 public EqualsTester(StandardSubjectBuilder expect) { 29 mExpect = Objects.requireNonNull(expect); 30 } 31 32 // TODO(b/336615269): refactor to take Object... instead 33 /** 34 * Helper method that uses {@code expect} to assert the class properly implement {@code 35 * equals()} and {@code hashCode()}. 36 * 37 * @param obj1 object that is equals to {@code obj2} 38 * @param obj2 object that is equals to {@code obj1} 39 */ expectObjectsAreEqual(Object obj1, Object obj2)40 public void expectObjectsAreEqual(Object obj1, Object obj2) { 41 Objects.requireNonNull(obj1, "1st arg cannot be null"); 42 Objects.requireNonNull(obj2, "2nd arg cannot be null"); 43 44 mExpect.withMessage("1st obj (%s)", obj1).that(obj1).isEqualTo(obj2); 45 mExpect.withMessage("2nd obj (%s)", obj2).that(obj2).isEqualTo(obj1); 46 mExpect.withMessage("hashCode of %s", obj1) 47 .that(obj1.hashCode()) 48 .isEqualTo(obj2.hashCode()); 49 } 50 51 // TODO(b/336615269): refactor to take Object... instead 52 /** 53 * Helper method that uses {@code expect} to assert the class properly implement {@code 54 * equals()}. 55 * 56 * @param obj1 object that is not equal to {@code obj2} 57 * @param obj2 object that is not equal to {@code obj1} 58 */ expectObjectsAreNotEqual(Object obj1, @Nullable Object obj2)59 public void expectObjectsAreNotEqual(Object obj1, @Nullable Object obj2) { 60 Objects.requireNonNull(obj1, "1st arg cannot be null"); 61 62 mExpect.withMessage("1st obj (%s)", obj1).that(obj1).isNotEqualTo(obj2); 63 mExpect.withMessage("2nd obj (%s)", obj2).that(obj2).isNotEqualTo(obj1); 64 } 65 } 66