Java

Форк
0
/
ClassSanityTesterTest.java 
1342 строки · 36.2 Кб
1
/*
2
 * Copyright (C) 2012 The Guava Authors
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.google.common.testing;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20
import static com.google.common.truth.Truth.assertThat;
21
import static org.junit.Assert.assertThrows;
22

23
import com.google.common.base.Functions;
24
import com.google.common.base.Optional;
25
import com.google.common.collect.ImmutableList;
26
import com.google.common.testing.ClassSanityTester.FactoryMethodReturnsNullException;
27
import com.google.common.testing.ClassSanityTester.ParameterHasNoDistinctValueException;
28
import com.google.common.testing.ClassSanityTester.ParameterNotInstantiableException;
29
import com.google.common.testing.NullPointerTester.Visibility;
30
import java.io.Serializable;
31
import java.lang.reflect.InvocationTargetException;
32
import java.util.AbstractList;
33
import java.util.ArrayList;
34
import java.util.List;
35
import java.util.Map;
36
import java.util.Set;
37
import java.util.concurrent.TimeUnit;
38
import java.util.stream.Collectors;
39
import java.util.stream.Stream;
40
import junit.framework.TestCase;
41
import org.checkerframework.checker.nullness.qual.Nullable;
42

43
/**
44
 * Unit tests for {@link ClassSanityTester}.
45
 *
46
 * @author Ben Yu
47
 */
48
public class ClassSanityTesterTest extends TestCase {
49

50
  private final ClassSanityTester tester = new ClassSanityTester();
51

52
  public void testEqualsOnReturnValues_good() throws Exception {
53
    tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEquals();
54
  }
55

56
  public static class GoodEqualsFactory {
57
    public static Object good(
58
        String a,
59
        int b,
60
        // oneConstantOnly doesn't matter since it's not nullable and can be only 1 value.
61
        @SuppressWarnings("unused") OneConstantEnum oneConstantOnly,
62
        // noConstant doesn't matter since it can only be null
63
        @SuppressWarnings("unused") @Nullable NoConstantEnum noConstant) {
64
      return new GoodEquals(a, b);
65
    }
66

67
    // instance method ignored
68
    public Object badIgnored() {
69
      return new BadEquals();
70
    }
71

72
    // primitive ignored
73
    public int returnsInt() {
74
      throw new UnsupportedOperationException();
75
    }
76

77
    // void ignored
78
    public void voidMethod() {
79
      throw new UnsupportedOperationException();
80
    }
81

82
    // non-public method ignored
83
    static Object badButNotPublic() {
84
      return new BadEquals();
85
    }
86
  }
87

88
  public void testForAllPublicStaticMethods_noPublicStaticMethods() throws Exception {
89
    try {
90
      tester.forAllPublicStaticMethods(NoPublicStaticMethods.class).testEquals();
91
    } catch (AssertionError expected) {
92
      assertThat(expected)
93
          .hasMessageThat()
94
          .isEqualTo(
95
              "No public static methods that return java.lang.Object or subtype are found in "
96
                  + NoPublicStaticMethods.class
97
                  + ".");
98
      return;
99
    }
100
    fail();
101
  }
102

103
  public void testEqualsOnReturnValues_bad() throws Exception {
104
    try {
105
      tester.forAllPublicStaticMethods(BadEqualsFactory.class).testEquals();
106
    } catch (AssertionError expected) {
107
      return;
108
    }
109
    fail();
110
  }
111

112
  private static class BadEqualsFactory {
113
    /** oneConstantOnly matters now since it can be either null or the constant. */
114
    @SuppressWarnings("unused") // Called by reflection
115
    public static Object bad(String a, int b, @Nullable OneConstantEnum oneConstantOnly) {
116
      return new GoodEquals(a, b);
117
    }
118
  }
119

120
  public void testNullsOnReturnValues_good() throws Exception {
121
    tester.forAllPublicStaticMethods(GoodNullsFactory.class).testNulls();
122
  }
123

124
  private static class GoodNullsFactory {
125
    @SuppressWarnings("unused") // Called by reflection
126
    public static Object good(String s) {
127
      return new GoodNulls(s);
128
    }
129
  }
130

131
  public void testNullsOnReturnValues_bad() throws Exception {
132
    try {
133
      tester.forAllPublicStaticMethods(BadNullsFactory.class).thatReturn(Object.class).testNulls();
134
    } catch (AssertionError expected) {
135
      return;
136
    }
137
    fail();
138
  }
139

140
  public void testNullsOnReturnValues_returnTypeFiltered() throws Exception {
141
    try {
142
      tester
143
          .forAllPublicStaticMethods(BadNullsFactory.class)
144
          .thatReturn(Iterable.class)
145
          .testNulls();
146
    } catch (AssertionError expected) {
147
      assertThat(expected)
148
          .hasMessageThat()
149
          .isEqualTo(
150
              "No public static methods that return java.lang.Iterable or subtype are found in "
151
                  + BadNullsFactory.class
152
                  + ".");
153
      return;
154
    }
155
    fail();
156
  }
157

158
  public static class BadNullsFactory {
159
    public static Object bad(@SuppressWarnings("unused") String a) {
160
      return new BadNulls();
161
    }
162
  }
163

164
  @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface
165
  public void testSerializableOnReturnValues_good() throws Exception {
166
    tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testSerializable();
167
  }
168

169
  public static class GoodSerializableFactory {
170
    public static Object good(Runnable r) {
171
      return r;
172
    }
173

174
    public static Object good(AnInterface i) {
175
      return i;
176
    }
177
  }
178

179
  public void testSerializableOnReturnValues_bad() throws Exception {
180
    try {
181
      tester.forAllPublicStaticMethods(BadSerializableFactory.class).testSerializable();
182
    } catch (AssertionError expected) {
183
      return;
184
    }
185
    fail();
186
  }
187

188
  public static class BadSerializableFactory {
189
    public static Object bad() {
190
      return new Serializable() {
191
        @SuppressWarnings("unused")
192
        private final Object notSerializable = new Object();
193
      };
194
    }
195
  }
196

197
  public void testEqualsAndSerializableOnReturnValues_equalsIsGoodButNotSerializable()
198
      throws Exception {
199
    try {
200
      tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEqualsAndSerializable();
201
    } catch (AssertionError expected) {
202
      return;
203
    }
204
    fail("should have failed");
205
  }
206

207
  public void testEqualsAndSerializableOnReturnValues_serializableButNotEquals() throws Exception {
208
    try {
209
      tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testEqualsAndSerializable();
210
    } catch (AssertionError expected) {
211
      return;
212
    }
213
    fail("should have failed");
214
  }
215

216
  @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface
217
  public void testEqualsAndSerializableOnReturnValues_good() throws Exception {
218
    tester
219
        .forAllPublicStaticMethods(GoodEqualsAndSerializableFactory.class)
220
        .testEqualsAndSerializable();
221
  }
222

223
  public static class GoodEqualsAndSerializableFactory {
224
    public static Object good(AnInterface s) {
225
      return Functions.constant(s);
226
    }
227
  }
228

229
  public void testEqualsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception {
230
    try {
231
      tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class).testEquals();
232
    } catch (AssertionError expected) {
233
      return;
234
    }
235
    fail();
236
  }
237

238
  public void testNullsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception {
239
    try {
240
      tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class).testNulls();
241
    } catch (AssertionError expected) {
242
      return;
243
    }
244
    fail();
245
  }
246

247
  public void testSerializableForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception {
248
    try {
249
      tester
250
          .forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class)
251
          .testSerializable();
252
    } catch (AssertionError expected) {
253
      return;
254
    }
255
    fail();
256
  }
257

258
  public void testEqualsAndSerializableForReturnValues_factoryReturnsNullButNotAnnotated()
259
      throws Exception {
260
    try {
261
      tester
262
          .forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class)
263
          .testEqualsAndSerializable();
264
    } catch (AssertionError expected) {
265
      return;
266
    }
267
    fail();
268
  }
269

270
  public static class FactoryThatReturnsNullButNotAnnotated {
271
    public static Object bad() {
272
      return null;
273
    }
274
  }
275

276
  public void testEqualsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception {
277
    tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testEquals();
278
  }
279

280
  public void testNullsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception {
281
    tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testNulls();
282
  }
283

284
  public void testSerializableForReturnValues_factoryReturnsNullAndAnnotated() throws Exception {
285
    tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testSerializable();
286
  }
287

288
  public void testEqualsAndSerializableForReturnValues_factoryReturnsNullAndAnnotated()
289
      throws Exception {
290
    tester
291
        .forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class)
292
        .testEqualsAndSerializable();
293
  }
294

295
  public static class FactoryThatReturnsNullAndAnnotated {
296
    public static @Nullable Object bad() {
297
      return null;
298
    }
299
  }
300

301
  public void testGoodEquals() throws Exception {
302
    tester.testEquals(GoodEquals.class);
303
  }
304

305
  public void testEquals_interface() {
306
    tester.testEquals(AnInterface.class);
307
  }
308

309
  public void testEquals_abstractClass() {
310
    tester.testEquals(AnAbstractClass.class);
311
  }
312

313
  public void testEquals_enum() {
314
    tester.testEquals(OneConstantEnum.class);
315
  }
316

317
  public void testBadEquals() throws Exception {
318
    try {
319
      tester.testEquals(BadEquals.class);
320
    } catch (AssertionError expected) {
321
      assertThat(expected).hasMessageThat().contains("create(null)");
322
      return;
323
    }
324
    fail("should have failed");
325
  }
326

327
  public void testBadEquals_withParameterizedType() throws Exception {
328
    try {
329
      tester.testEquals(BadEqualsWithParameterizedType.class);
330
    } catch (AssertionError expected) {
331
      assertThat(expected).hasMessageThat().contains("create([[1]])");
332
      return;
333
    }
334
    fail("should have failed");
335
  }
336

337
  public void testBadEquals_withSingleParameterValue() throws Exception {
338
    assertThrows(
339
        ParameterHasNoDistinctValueException.class,
340
        () -> tester.doTestEquals(ConstructorParameterWithOptionalNotInstantiable.class));
341
  }
342

343
  public void testGoodReferentialEqualityComparison() throws Exception {
344
    tester.testEquals(UsesEnum.class);
345
    tester.testEquals(UsesReferentialEquality.class);
346
    tester.testEquals(SameListInstance.class);
347
  }
348

349
  public void testStreamParameterSkippedForNullTesting() throws Exception {
350
    tester.testNulls(WithStreamParameter.class);
351
  }
352

353
  @AndroidIncompatible // problem with equality of Type objects?
354
  public void testEqualsUsingReferentialEquality() throws Exception {
355
    assertBadUseOfReferentialEquality(SameIntegerInstance.class);
356
    assertBadUseOfReferentialEquality(SameLongInstance.class);
357
    assertBadUseOfReferentialEquality(SameFloatInstance.class);
358
    assertBadUseOfReferentialEquality(SameDoubleInstance.class);
359
    assertBadUseOfReferentialEquality(SameShortInstance.class);
360
    assertBadUseOfReferentialEquality(SameByteInstance.class);
361
    assertBadUseOfReferentialEquality(SameCharacterInstance.class);
362
    assertBadUseOfReferentialEquality(SameBooleanInstance.class);
363
    assertBadUseOfReferentialEquality(SameObjectInstance.class);
364
    assertBadUseOfReferentialEquality(SameStringInstance.class);
365
    assertBadUseOfReferentialEquality(SameInterfaceInstance.class);
366
  }
367

368
  private void assertBadUseOfReferentialEquality(Class<?> cls) throws Exception {
369
    try {
370
      tester.testEquals(cls);
371
    } catch (AssertionError expected) {
372
      assertThat(expected).hasMessageThat().contains(cls.getSimpleName() + "(");
373
      return;
374
    }
375
    fail("should have failed for " + cls);
376
  }
377

378
  public void testParameterNotInstantiableForEqualsTest() throws Exception {
379
    assertThrows(
380
        ParameterNotInstantiableException.class,
381
        () -> tester.doTestEquals(ConstructorParameterNotInstantiable.class));
382
  }
383

384
  public void testNoDistinctValueForEqualsTest() throws Exception {
385
    assertThrows(
386
        ParameterHasNoDistinctValueException.class,
387
        () -> tester.doTestEquals(ConstructorParameterSingleValue.class));
388
  }
389

390
  public void testConstructorThrowsForEqualsTest() throws Exception {
391
    assertThrows(
392
        InvocationTargetException.class, () -> tester.doTestEquals(ConstructorThrows.class));
393
  }
394

395
  public void testFactoryMethodReturnsNullForEqualsTest() throws Exception {
396
    assertThrows(
397
        FactoryMethodReturnsNullException.class,
398
        () -> tester.doTestEquals(FactoryMethodReturnsNullAndAnnotated.class));
399
  }
400

401
  public void testFactoryMethodReturnsNullButNotAnnotatedInEqualsTest() throws Exception {
402
    try {
403
      tester.testEquals(FactoryMethodReturnsNullButNotAnnotated.class);
404
    } catch (AssertionError expected) {
405
      return;
406
    }
407
    fail("should have failed");
408
  }
409

410
  public void testNoEqualsChecksOnEnum() throws Exception {
411
    tester.testEquals(OneConstantEnum.class);
412
    tester.testEquals(NoConstantEnum.class);
413
    tester.testEquals(TimeUnit.class);
414
  }
415

416
  public void testNoEqualsChecksOnInterface() throws Exception {
417
    tester.testEquals(Runnable.class);
418
  }
419

420
  public void testNoEqualsChecksOnAnnotation() throws Exception {
421
    tester.testEquals(MyAnnotation.class);
422
  }
423

424
  public void testGoodNulls() throws Exception {
425
    tester.testNulls(GoodNulls.class);
426
  }
427

428
  public void testNoNullCheckNeededDespiteNotInstantiable() throws Exception {
429
    tester.doTestNulls(NoNullCheckNeededDespiteNotInstantiable.class, Visibility.PACKAGE);
430
  }
431

432
  public void testNulls_interface() {
433
    tester.testNulls(AnInterface.class);
434
  }
435

436
  public void testNulls_abstractClass() {
437
    tester.testNulls(AnAbstractClass.class);
438
  }
439

440
  public void testNulls_enum() throws Exception {
441
    tester.testNulls(OneConstantEnum.class);
442
    tester.testNulls(NoConstantEnum.class);
443
    tester.testNulls(TimeUnit.class);
444
  }
445

446
  public void testNulls_parameterOptionalNotInstantiable() throws Exception {
447
    tester.testNulls(ConstructorParameterWithOptionalNotInstantiable.class);
448
  }
449

450
  public void testEnumFailsToCheckNull() throws Exception {
451
    try {
452
      tester.testNulls(EnumFailsToCheckNull.class);
453
    } catch (AssertionError expected) {
454
      return;
455
    }
456
    fail("should have failed");
457
  }
458

459
  public void testNoNullChecksOnInterface() throws Exception {
460
    tester.testNulls(Runnable.class);
461
  }
462

463
  public void testNoNullChecksOnAnnotation() throws Exception {
464
    tester.testNulls(MyAnnotation.class);
465
  }
466

467
  public void testBadNulls() throws Exception {
468
    try {
469
      tester.testNulls(BadNulls.class);
470
    } catch (AssertionError expected) {
471
      return;
472
    }
473
    fail("should have failed");
474
  }
475

476
  public void testInstantiate_factoryMethodReturnsNullButNotAnnotated() throws Exception {
477
    try {
478
      FactoryMethodReturnsNullButNotAnnotated unused =
479
          tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class);
480
    } catch (AssertionError expected) {
481
      assertThat(expected).hasMessageThat().contains("@Nullable");
482
      return;
483
    }
484
    fail("should have failed");
485
  }
486

487
  public void testInstantiate_factoryMethodReturnsNullAndAnnotated() throws Exception {
488
    assertThrows(
489
        FactoryMethodReturnsNullException.class,
490
        () -> tester.instantiate(FactoryMethodReturnsNullAndAnnotated.class));
491
  }
492

493
  public void testInstantiate_factoryMethodAcceptsNull() throws Exception {
494
    assertNull(tester.instantiate(FactoryMethodAcceptsNull.class).name);
495
  }
496

497
  public void testInstantiate_factoryMethodDoesNotAcceptNull() throws Exception {
498
    assertNotNull(tester.instantiate(FactoryMethodDoesNotAcceptNull.class).name);
499
  }
500

501
  public void testInstantiate_constructorAcceptsNull() throws Exception {
502
    assertNull(tester.instantiate(ConstructorAcceptsNull.class).name);
503
  }
504

505
  public void testInstantiate_constructorDoesNotAcceptNull() throws Exception {
506
    assertNotNull(tester.instantiate(ConstructorDoesNotAcceptNull.class).name);
507
  }
508

509
  public void testInstantiate_notInstantiable() throws Exception {
510
    assertNull(tester.instantiate(NotInstantiable.class));
511
  }
512

513
  public void testInstantiate_noConstantEnum() throws Exception {
514
    assertNull(tester.instantiate(NoConstantEnum.class));
515
  }
516

517
  public void testInstantiate_oneConstantEnum() throws Exception {
518
    assertEquals(OneConstantEnum.A, tester.instantiate(OneConstantEnum.class));
519
  }
520

521
  public void testInstantiate_interface() throws Exception {
522
    assertNull(tester.instantiate(Runnable.class));
523
  }
524

525
  public void testInstantiate_abstractClass() throws Exception {
526
    assertNull(tester.instantiate(AbstractList.class));
527
  }
528

529
  public void testInstantiate_annotation() throws Exception {
530
    assertNull(tester.instantiate(MyAnnotation.class));
531
  }
532

533
  public void testInstantiate_setDefault() throws Exception {
534
    NotInstantiable x = new NotInstantiable();
535
    tester.setDefault(NotInstantiable.class, x);
536
    assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class));
537
  }
538

539
  public void testSetDistinctValues_equalInstances() {
540
    assertThrows(
541
        IllegalArgumentException.class, () -> tester.setDistinctValues(String.class, "", ""));
542
  }
543

544
  public void testInstantiate_setDistinctValues() throws Exception {
545
    NotInstantiable x = new NotInstantiable();
546
    NotInstantiable y = new NotInstantiable();
547
    tester.setDistinctValues(NotInstantiable.class, x, y);
548
    assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class));
549
    tester.testEquals(ConstructorParameterMapOfNotInstantiable.class);
550
  }
551

552
  public void testInstantiate_constructorThrows() throws Exception {
553
    assertThrows(
554
        InvocationTargetException.class, () -> tester.instantiate(ConstructorThrows.class));
555
  }
556

557
  public void testInstantiate_factoryMethodThrows() throws Exception {
558
    assertThrows(
559
        InvocationTargetException.class, () -> tester.instantiate(FactoryMethodThrows.class));
560
  }
561

562
  public void testInstantiate_constructorParameterNotInstantiable() throws Exception {
563
    assertThrows(
564
        ParameterNotInstantiableException.class,
565
        () -> tester.instantiate(ConstructorParameterNotInstantiable.class));
566
  }
567

568
  public void testInstantiate_factoryMethodParameterNotInstantiable() throws Exception {
569
    assertThrows(
570
        ParameterNotInstantiableException.class,
571
        () -> tester.instantiate(FactoryMethodParameterNotInstantiable.class));
572
  }
573

574
  public void testInstantiate_instantiableFactoryMethodChosen() throws Exception {
575
    assertEquals("good", tester.instantiate(InstantiableFactoryMethodChosen.class).name);
576
  }
577

578
  @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface
579
  public void testInterfaceProxySerializable() throws Exception {
580
    SerializableTester.reserializeAndAssert(tester.instantiate(HasAnInterface.class));
581
  }
582

583
  public void testReturnValuesFromAnotherPackageIgnoredForNullTests() throws Exception {
584
    new ClassSanityTester().forAllPublicStaticMethods(JdkObjectFactory.class).testNulls();
585
  }
586

587
  /** String doesn't check nulls as we expect. But the framework should ignore. */
588
  private static class JdkObjectFactory {
589
    @SuppressWarnings("unused") // Called by reflection
590
    public static Object create() {
591
      return new ArrayList<>();
592
    }
593
  }
594

595
  static class HasAnInterface implements Serializable {
596
    private final AnInterface i;
597

598
    public HasAnInterface(AnInterface i) {
599
      this.i = i;
600
    }
601

602
    @Override
603
    public boolean equals(@Nullable Object obj) {
604
      if (obj instanceof HasAnInterface) {
605
        HasAnInterface that = (HasAnInterface) obj;
606
        return i.equals(that.i);
607
      } else {
608
        return false;
609
      }
610
    }
611

612
    @Override
613
    public int hashCode() {
614
      return i.hashCode();
615
    }
616
  }
617

618
  static class InstantiableFactoryMethodChosen {
619
    final String name;
620

621
    private InstantiableFactoryMethodChosen(String name) {
622
      this.name = name;
623
    }
624

625
    public InstantiableFactoryMethodChosen(NotInstantiable x) {
626
      checkNotNull(x);
627
      this.name = "x1";
628
    }
629

630
    public static InstantiableFactoryMethodChosen create(NotInstantiable x) {
631
      return new InstantiableFactoryMethodChosen(x);
632
    }
633

634
    public static InstantiableFactoryMethodChosen create(String s) {
635
      checkNotNull(s);
636
      return new InstantiableFactoryMethodChosen("good");
637
    }
638
  }
639

640
  public void testInstantiate_instantiableConstructorChosen() throws Exception {
641
    assertEquals("good", tester.instantiate(InstantiableConstructorChosen.class).name);
642
  }
643

644
  public void testEquals_setOfNonInstantiable() throws Exception {
645
    assertThrows(
646
        ParameterNotInstantiableException.class,
647
        () -> new ClassSanityTester().doTestEquals(SetWrapper.class));
648
  }
649

650
  private abstract static class Wrapper {
651
    private final Object wrapped;
652

653
    Wrapper(Object wrapped) {
654
      this.wrapped = checkNotNull(wrapped);
655
    }
656

657
    @Override
658
    public boolean equals(@Nullable Object obj) {
659
      // In general getClass().isInstance() is bad for equals.
660
      // But here we fully control the subclasses to ensure symmetry.
661
      if (getClass().isInstance(obj)) {
662
        Wrapper that = (Wrapper) obj;
663
        return wrapped.equals(that.wrapped);
664
      }
665
      return false;
666
    }
667

668
    @Override
669
    public int hashCode() {
670
      return wrapped.hashCode();
671
    }
672

673
    @Override
674
    public String toString() {
675
      return wrapped.toString();
676
    }
677
  }
678

679
  private static class SetWrapper extends Wrapper {
680
    public SetWrapper(Set<NotInstantiable> wrapped) {
681
      super(wrapped);
682
    }
683
  }
684

685
  static class InstantiableConstructorChosen {
686
    final String name;
687

688
    public InstantiableConstructorChosen(String name) {
689
      checkNotNull(name);
690
      this.name = "good";
691
    }
692

693
    public InstantiableConstructorChosen(NotInstantiable x) {
694
      checkNotNull(x);
695
      this.name = "x1";
696
    }
697

698
    public static InstantiableFactoryMethodChosen create(NotInstantiable x) {
699
      return new InstantiableFactoryMethodChosen(x);
700
    }
701
  }
702

703
  static class GoodEquals {
704

705
    private final String a;
706
    private final int b;
707

708
    private GoodEquals(String a, int b) {
709
      this.a = checkNotNull(a);
710
      this.b = b;
711
    }
712

713
    // ignored by testEquals()
714
    GoodEquals(@SuppressWarnings("unused") NotInstantiable x) {
715
      this.a = "x";
716
      this.b = -1;
717
    }
718

719
    // will keep trying
720
    public GoodEquals(@SuppressWarnings("unused") NotInstantiable x, int b) {
721
      this.a = "x";
722
      this.b = b;
723
    }
724

725
    // keep trying
726
    @SuppressWarnings("unused")
727
    static GoodEquals create(int a, int b) {
728
      throw new RuntimeException();
729
    }
730

731
    // Good!
732
    static GoodEquals create(String a, int b) {
733
      return new GoodEquals(a, b);
734
    }
735

736
    // keep trying
737
    @SuppressWarnings("unused")
738
    public static @Nullable GoodEquals createMayReturnNull(int a, int b) {
739
      return null;
740
    }
741

742
    @Override
743
    public boolean equals(@Nullable Object obj) {
744
      if (obj instanceof GoodEquals) {
745
        GoodEquals that = (GoodEquals) obj;
746
        return a.equals(that.a) && b == that.b;
747
      } else {
748
        return false;
749
      }
750
    }
751

752
    @Override
753
    public int hashCode() {
754
      return 0;
755
    }
756
  }
757

758
  static class BadEquals {
759

760
    public BadEquals() {} // ignored by testEquals() since it has less parameters.
761

762
    public static BadEquals create(@SuppressWarnings("unused") @Nullable String s) {
763
      return new BadEquals();
764
    }
765

766
    @Override
767
    public boolean equals(@Nullable Object obj) {
768
      return obj instanceof BadEquals;
769
    }
770

771
    @Override
772
    public int hashCode() {
773
      return 0;
774
    }
775
  }
776

777
  static class SameIntegerInstance {
778
    private final Integer i;
779

780
    public SameIntegerInstance(Integer i) {
781
      this.i = checkNotNull(i);
782
    }
783

784
    @Override
785
    public int hashCode() {
786
      return i.hashCode();
787
    }
788

789
    @Override
790
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
791
    public boolean equals(@Nullable Object obj) {
792
      if (obj instanceof SameIntegerInstance) {
793
        SameIntegerInstance that = (SameIntegerInstance) obj;
794
        return i == that.i;
795
      }
796
      return false;
797
    }
798
  }
799

800
  static class SameLongInstance {
801
    private final Long i;
802

803
    public SameLongInstance(Long i) {
804
      this.i = checkNotNull(i);
805
    }
806

807
    @Override
808
    public int hashCode() {
809
      return i.hashCode();
810
    }
811

812
    @Override
813
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
814
    public boolean equals(@Nullable Object obj) {
815
      if (obj instanceof SameLongInstance) {
816
        SameLongInstance that = (SameLongInstance) obj;
817
        return i == that.i;
818
      }
819
      return false;
820
    }
821
  }
822

823
  static class SameFloatInstance {
824
    private final Float i;
825

826
    public SameFloatInstance(Float i) {
827
      this.i = checkNotNull(i);
828
    }
829

830
    @Override
831
    public int hashCode() {
832
      return i.hashCode();
833
    }
834

835
    @Override
836
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
837
    public boolean equals(@Nullable Object obj) {
838
      if (obj instanceof SameFloatInstance) {
839
        SameFloatInstance that = (SameFloatInstance) obj;
840
        return i == that.i;
841
      }
842
      return false;
843
    }
844
  }
845

846
  static class SameDoubleInstance {
847
    private final Double i;
848

849
    public SameDoubleInstance(Double i) {
850
      this.i = checkNotNull(i);
851
    }
852

853
    @Override
854
    public int hashCode() {
855
      return i.hashCode();
856
    }
857

858
    @Override
859
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
860
    public boolean equals(@Nullable Object obj) {
861
      if (obj instanceof SameDoubleInstance) {
862
        SameDoubleInstance that = (SameDoubleInstance) obj;
863
        return i == that.i;
864
      }
865
      return false;
866
    }
867
  }
868

869
  static class SameShortInstance {
870
    private final Short i;
871

872
    public SameShortInstance(Short i) {
873
      this.i = checkNotNull(i);
874
    }
875

876
    @Override
877
    public int hashCode() {
878
      return i.hashCode();
879
    }
880

881
    @Override
882
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
883
    public boolean equals(@Nullable Object obj) {
884
      if (obj instanceof SameShortInstance) {
885
        SameShortInstance that = (SameShortInstance) obj;
886
        return i == that.i;
887
      }
888
      return false;
889
    }
890
  }
891

892
  static class SameByteInstance {
893
    private final Byte i;
894

895
    public SameByteInstance(Byte i) {
896
      this.i = checkNotNull(i);
897
    }
898

899
    @Override
900
    public int hashCode() {
901
      return i.hashCode();
902
    }
903

904
    @Override
905
    @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
906
    public boolean equals(@Nullable Object obj) {
907
      if (obj instanceof SameByteInstance) {
908
        SameByteInstance that = (SameByteInstance) obj;
909
        return i == that.i;
910
      }
911
      return false;
912
    }
913
  }
914

915
  static class SameCharacterInstance {
916
    private final Character i;
917

918
    public SameCharacterInstance(Character i) {
919
      this.i = checkNotNull(i);
920
    }
921

922
    @Override
923
    public int hashCode() {
924
      return i.hashCode();
925
    }
926

927
    @Override
928
    @SuppressWarnings("BoxedPrimitiveEquality")
929
    public boolean equals(@Nullable Object obj) {
930
      if (obj instanceof SameCharacterInstance) {
931
        SameCharacterInstance that = (SameCharacterInstance) obj;
932
        return i == that.i;
933
      }
934
      return false;
935
    }
936
  }
937

938
  static class SameBooleanInstance {
939
    private final Boolean i;
940

941
    public SameBooleanInstance(Boolean i) {
942
      this.i = checkNotNull(i);
943
    }
944

945
    @Override
946
    public int hashCode() {
947
      return i.hashCode();
948
    }
949

950
    @Override
951
    @SuppressWarnings("BoxedPrimitiveEquality")
952
    public boolean equals(@Nullable Object obj) {
953
      if (obj instanceof SameBooleanInstance) {
954
        SameBooleanInstance that = (SameBooleanInstance) obj;
955
        return i == that.i;
956
      }
957
      return false;
958
    }
959
  }
960

961
  static class SameStringInstance {
962
    private final String s;
963

964
    public SameStringInstance(String s) {
965
      this.s = checkNotNull(s);
966
    }
967

968
    @Override
969
    public int hashCode() {
970
      return s.hashCode();
971
    }
972

973
    @Override
974
    public boolean equals(@Nullable Object obj) {
975
      if (obj instanceof SameStringInstance) {
976
        SameStringInstance that = (SameStringInstance) obj;
977
        return s == that.s;
978
      }
979
      return false;
980
    }
981
  }
982

983
  static class SameObjectInstance {
984
    private final Object s;
985

986
    public SameObjectInstance(Object s) {
987
      this.s = checkNotNull(s);
988
    }
989

990
    @Override
991
    public int hashCode() {
992
      return s.hashCode();
993
    }
994

995
    @Override
996
    public boolean equals(@Nullable Object obj) {
997
      if (obj instanceof SameObjectInstance) {
998
        SameObjectInstance that = (SameObjectInstance) obj;
999
        return s == that.s;
1000
      }
1001
      return false;
1002
    }
1003
  }
1004

1005
  static class SameInterfaceInstance {
1006
    private final Runnable s;
1007

1008
    public SameInterfaceInstance(Runnable s) {
1009
      this.s = checkNotNull(s);
1010
    }
1011

1012
    @Override
1013
    public int hashCode() {
1014
      return s.hashCode();
1015
    }
1016

1017
    @Override
1018
    public boolean equals(@Nullable Object obj) {
1019
      if (obj instanceof SameInterfaceInstance) {
1020
        SameInterfaceInstance that = (SameInterfaceInstance) obj;
1021
        return s == that.s;
1022
      }
1023
      return false;
1024
    }
1025
  }
1026

1027
  static class SameListInstance {
1028
    private final List<?> s;
1029

1030
    public SameListInstance(List<?> s) {
1031
      this.s = checkNotNull(s);
1032
    }
1033

1034
    @Override
1035
    public int hashCode() {
1036
      return System.identityHashCode(s);
1037
    }
1038

1039
    @Override
1040
    public boolean equals(@Nullable Object obj) {
1041
      if (obj instanceof SameListInstance) {
1042
        SameListInstance that = (SameListInstance) obj;
1043
        return s == that.s;
1044
      }
1045
      return false;
1046
    }
1047
  }
1048

1049
  static class WithStreamParameter {
1050
    private final List<?> list;
1051

1052
    // This should be ignored.
1053
    public WithStreamParameter(Stream<?> s, String str) {
1054
      this.list = s.collect(Collectors.toList());
1055
      checkNotNull(str);
1056
    }
1057
  }
1058

1059
  static class UsesReferentialEquality {
1060
    private final ReferentialEquality s;
1061

1062
    public UsesReferentialEquality(ReferentialEquality s) {
1063
      this.s = checkNotNull(s);
1064
    }
1065

1066
    @Override
1067
    public int hashCode() {
1068
      return s.hashCode();
1069
    }
1070

1071
    @Override
1072
    public boolean equals(@Nullable Object obj) {
1073
      if (obj instanceof UsesReferentialEquality) {
1074
        UsesReferentialEquality that = (UsesReferentialEquality) obj;
1075
        return s == that.s;
1076
      }
1077
      return false;
1078
    }
1079
  }
1080

1081
  static class UsesEnum {
1082
    private final TimeUnit s;
1083

1084
    public UsesEnum(TimeUnit s) {
1085
      this.s = checkNotNull(s);
1086
    }
1087

1088
    @Override
1089
    public int hashCode() {
1090
      return s.hashCode();
1091
    }
1092

1093
    @Override
1094
    public boolean equals(@Nullable Object obj) {
1095
      if (obj instanceof UsesEnum) {
1096
        UsesEnum that = (UsesEnum) obj;
1097
        return s == that.s;
1098
      }
1099
      return false;
1100
    }
1101
  }
1102

1103
  public static class ReferentialEquality {
1104
    public ReferentialEquality() {}
1105
  }
1106

1107
  static class BadEqualsWithParameterizedType {
1108

1109
    // ignored by testEquals() since it has less parameters.
1110
    public BadEqualsWithParameterizedType() {}
1111

1112
    public static BadEqualsWithParameterizedType create(
1113
        @SuppressWarnings("unused") ImmutableList<Iterable<? extends String>> s) {
1114
      return new BadEqualsWithParameterizedType();
1115
    }
1116

1117
    @Override
1118
    public boolean equals(@Nullable Object obj) {
1119
      return obj instanceof BadEqualsWithParameterizedType;
1120
    }
1121

1122
    @Override
1123
    public int hashCode() {
1124
      return 0;
1125
    }
1126
  }
1127

1128
  static class GoodNulls {
1129
    public GoodNulls(String s) {
1130
      checkNotNull(s);
1131
    }
1132

1133
    public void rejectNull(String s) {
1134
      checkNotNull(s);
1135
    }
1136
  }
1137

1138
  public static class BadNulls {
1139
    public void failsToRejectNull(@SuppressWarnings("unused") String s) {}
1140
  }
1141

1142
  public static class NoNullCheckNeededDespiteNotInstantiable {
1143

1144
    public NoNullCheckNeededDespiteNotInstantiable(NotInstantiable x) {
1145
      checkNotNull(x);
1146
    }
1147

1148
    @SuppressWarnings("unused") // reflected
1149
    void primitiveOnly(int i) {}
1150

1151
    @SuppressWarnings("unused") // reflected
1152
    void nullableOnly(@Nullable String s) {}
1153

1154
    public void noParameter() {}
1155

1156
    @SuppressWarnings("unused") // reflected
1157
    void primitiveAndNullable(@Nullable String s, int i) {}
1158
  }
1159

1160
  static class FactoryMethodReturnsNullButNotAnnotated {
1161
    private FactoryMethodReturnsNullButNotAnnotated() {}
1162

1163
    static FactoryMethodReturnsNullButNotAnnotated returnsNull() {
1164
      return null;
1165
    }
1166
  }
1167

1168
  static class FactoryMethodReturnsNullAndAnnotated {
1169
    private FactoryMethodReturnsNullAndAnnotated() {}
1170

1171
    public static @Nullable FactoryMethodReturnsNullAndAnnotated returnsNull() {
1172
      return null;
1173
    }
1174
  }
1175

1176
  static class FactoryMethodAcceptsNull {
1177

1178
    final String name;
1179

1180
    private FactoryMethodAcceptsNull(String name) {
1181
      this.name = name;
1182
    }
1183

1184
    static FactoryMethodAcceptsNull create(@Nullable String name) {
1185
      return new FactoryMethodAcceptsNull(name);
1186
    }
1187
  }
1188

1189
  static class FactoryMethodDoesNotAcceptNull {
1190

1191
    final String name;
1192

1193
    private FactoryMethodDoesNotAcceptNull(String name) {
1194
      this.name = checkNotNull(name);
1195
    }
1196

1197
    public static FactoryMethodDoesNotAcceptNull create(String name) {
1198
      return new FactoryMethodDoesNotAcceptNull(name);
1199
    }
1200
  }
1201

1202
  static class ConstructorAcceptsNull {
1203

1204
    final String name;
1205

1206
    public ConstructorAcceptsNull(@Nullable String name) {
1207
      this.name = name;
1208
    }
1209
  }
1210

1211
  static class ConstructorDoesNotAcceptNull {
1212

1213
    final String name;
1214

1215
    ConstructorDoesNotAcceptNull(String name) {
1216
      this.name = checkNotNull(name);
1217
    }
1218
  }
1219

1220
  static class ConstructorParameterNotInstantiable {
1221
    public ConstructorParameterNotInstantiable(@SuppressWarnings("unused") NotInstantiable x) {}
1222
  }
1223

1224
  static class ConstructorParameterMapOfNotInstantiable {
1225
    private final Map<NotInstantiable, NotInstantiable> m;
1226

1227
    public ConstructorParameterMapOfNotInstantiable(Map<NotInstantiable, NotInstantiable> m) {
1228
      this.m = checkNotNull(m);
1229
    }
1230

1231
    @Override
1232
    public boolean equals(@Nullable Object obj) {
1233
      if (obj instanceof ConstructorParameterMapOfNotInstantiable) {
1234
        return m.equals(((ConstructorParameterMapOfNotInstantiable) obj).m);
1235
      } else {
1236
        return false;
1237
      }
1238
    }
1239

1240
    @Override
1241
    public int hashCode() {
1242
      return m.hashCode();
1243
    }
1244
  }
1245

1246
  // Test that we should get a distinct parameter error when doing equals test.
1247
  static class ConstructorParameterWithOptionalNotInstantiable {
1248
    public ConstructorParameterWithOptionalNotInstantiable(Optional<NotInstantiable> x) {
1249
      checkNotNull(x);
1250
    }
1251

1252
    @Override
1253
    public boolean equals(@Nullable Object obj) {
1254
      throw new UnsupportedOperationException();
1255
    }
1256

1257
    @Override
1258
    public int hashCode() {
1259
      throw new UnsupportedOperationException();
1260
    }
1261
  }
1262

1263
  static class ConstructorParameterSingleValue {
1264
    public ConstructorParameterSingleValue(@SuppressWarnings("unused") Singleton s) {}
1265

1266
    @Override
1267
    public boolean equals(@Nullable Object obj) {
1268
      return obj instanceof ConstructorParameterSingleValue;
1269
    }
1270

1271
    @Override
1272
    public int hashCode() {
1273
      return 1;
1274
    }
1275

1276
    public static class Singleton {
1277
      public static final Singleton INSTANCE = new Singleton();
1278

1279
      private Singleton() {}
1280
    }
1281
  }
1282

1283
  static class FactoryMethodParameterNotInstantiable {
1284

1285
    private FactoryMethodParameterNotInstantiable() {}
1286

1287
    static FactoryMethodParameterNotInstantiable create(
1288
        @SuppressWarnings("unused") NotInstantiable x) {
1289
      return new FactoryMethodParameterNotInstantiable();
1290
    }
1291
  }
1292

1293
  static class ConstructorThrows {
1294
    public ConstructorThrows() {
1295
      throw new RuntimeException();
1296
    }
1297
  }
1298

1299
  static class FactoryMethodThrows {
1300
    private FactoryMethodThrows() {}
1301

1302
    public static FactoryMethodThrows create() {
1303
      throw new RuntimeException();
1304
    }
1305
  }
1306

1307
  static class NotInstantiable {
1308
    private NotInstantiable() {}
1309
  }
1310

1311
  private enum NoConstantEnum {}
1312

1313
  private enum OneConstantEnum {
1314
    A
1315
  }
1316

1317
  private enum EnumFailsToCheckNull {
1318
    A;
1319

1320
    @SuppressWarnings("unused")
1321
    public void failToCheckNull(String s) {}
1322
  }
1323

1324
  private interface AnInterface {}
1325

1326
  private abstract static class AnAbstractClass {
1327
    @SuppressWarnings("unused")
1328
    public AnAbstractClass(String s) {}
1329

1330
    @SuppressWarnings("unused")
1331
    public void failsToCheckNull(String s) {}
1332
  }
1333

1334
  private static class NoPublicStaticMethods {
1335
    @SuppressWarnings("unused") // To test non-public factory isn't used.
1336
    static String notPublic() {
1337
      return "";
1338
    }
1339
  }
1340

1341
  @interface MyAnnotation {}
1342
}
1343

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.