1 /*
2 * MIT License
3 * Copyright (c) 2006-2025 JMockit developers
4 * See LICENSE file for full license text.
5 */
6 package mockit;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9
10 import java.awt.Component;
11
12 import org.junit.jupiter.api.Test;
13
14 /**
15 * The Class MisusedFakingAPITest.
16 */
17 final class MisusedFakingAPITest {
18
19 // Lightweight test-only class to be mocked.
20 public static class SimpleComponent {
21 public int getComponentCount() {
22 return 0;
23 }
24 }
25
26 /**
27 * Fake same method twice with reentrant fakes from two different fake classes.
28 */
29 @Test
30 void fakeSameMethodTwiceWithReentrantFakesFromTwoDifferentFakeClasses() {
31 new MockUp<SimpleComponent>() {
32 @Mock
33 int getComponentCount(Invocation inv) {
34 int i = inv.proceed();
35 return i + 1;
36 }
37 };
38
39 int i = new SimpleComponent().getComponentCount();
40 assertEquals(1, i);
41
42 new MockUp<SimpleComponent>() {
43 @Mock
44 int getComponentCount(Invocation inv) {
45 int j = inv.proceed();
46 return j + 2;
47 }
48 };
49
50 // Should return 3, but returns 5. Chaining mock methods is not supported.
51 int j = new SimpleComponent().getComponentCount();
52 assertEquals(5, j);
53 }
54
55 /**
56 * The Class SimpleComponentFake.
57 */
58 static final class SimpleComponentFake extends MockUp<SimpleComponent> {
59
60 /** The component count. */
61 final int componentCount;
62
63 /**
64 * Instantiates a new simple component fake.
65 *
66 * @param componentCount
67 * the component count
68 */
69 SimpleComponentFake(int componentCount) {
70 this.componentCount = componentCount;
71 }
72
73 /**
74 * Gets the component count.
75 *
76 * @param inv
77 * the inv
78 *
79 * @return the component count
80 */
81 @Mock
82 int getComponentCount(Invocation inv) {
83 return componentCount;
84 }
85 }
86
87 /**
88 * Apply the same fake for A class twice.
89 */
90 @Test
91 void applyTheSameFakeForAClassTwice() {
92 new SimpleComponentFake(1);
93 new SimpleComponentFake(2); // second application overrides the previous one
94
95 assertEquals(2, new SimpleComponent().getComponentCount());
96 }
97
98 /**
99 * Fake A private method.
100 */
101 @Test
102 void fakeAPrivateMethod() {
103 // Changed to allow fake private constructors.
104 new MockUp<Component>() {
105 @Mock
106 boolean checkCoalescing() {
107 return false;
108 }
109 };
110 }
111
112 /**
113 * Fake A private constructor.
114 */
115 @Test
116 public void fakeAPrivateConstructor() {
117 // Changed to allow fake private constructors.
118 new MockUp<System>() {
119 @Mock
120 void $init() {
121 }
122 };
123 }
124 }