View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3.builder;
19  
20  import static org.junit.jupiter.api.Assertions.assertTrue;
21  
22  import org.junit.jupiter.api.Test;
23  
24  /**
25   * Tests {@link EqualsBuilder#reflectionEquals(Object, Object, String...)}.
26   * <p>
27   * reflectionEquals array fix enables cyclic-array.
28   * </p>
29   * <p>
30   * Pre-patch: Object[] elements containing themselves cause StackOverflowError when compared via EqualsBuilder.reflectionEquals because the array branch in
31   * reflectionAppend calls append(lhs, rhs) which recurses without cycle check.
32   * </p>
33   * <p>
34   * Post-patch: the arrays are registered before recursing so cycles are detected and the comparison terminates (returning false).
35   * </p>
36   */
37  class EqualsBuilderReflectionEqualsCycleTest {
38  
39      @Test
40      void testCrossReferentialObjectArrays() {
41          final Object[] a = new Object[1];
42          final Object[] b = new Object[1];
43          // a[0] -> b, b[0] -> a: mutual cycle
44          a[0] = b;
45          b[0] = a;
46          assertTrue(EqualsBuilder.reflectionEquals(a, b));
47      }
48  
49      @Test
50      void testSelfReferentialObjectArrays() {
51          final Object[] a = new Object[1];
52          final Object[] b = new Object[1];
53          a[0] = a;
54          b[0] = b;
55          // Pre-patch: StackOverflowError; Post-patch: terminates without error.
56          // With cycle detection, comparing a[0]=a vs b[0]=b sees (a,b) already registered
57          // and treats the cycle as equal, so the overall result is true (structurally isomorphic).
58          // The key assertion is that NO StackOverflowError is thrown.
59          assertTrue(EqualsBuilder.reflectionEquals(a, b));
60      }
61  }