Java

Форк
0
200 строк · 6.5 Кб
1
/*
2
 * Copyright (C) 2016 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.collect.testing.testers;
18

19
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
20
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
21
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
22
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
23
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
24

25
import com.google.common.annotations.GwtCompatible;
26
import com.google.common.annotations.GwtIncompatible;
27
import com.google.common.annotations.J2ktIncompatible;
28
import com.google.common.collect.testing.AbstractMapTester;
29
import com.google.common.collect.testing.Helpers;
30
import com.google.common.collect.testing.features.CollectionSize;
31
import com.google.common.collect.testing.features.MapFeature;
32
import java.lang.reflect.Method;
33
import java.util.Hashtable;
34
import java.util.Map;
35
import junit.framework.AssertionFailedError;
36
import org.junit.Ignore;
37

38
/**
39
 * A generic JUnit test which tests {@link Map#merge}. Can't be invoked directly; please see {@link
40
 * com.google.common.collect.testing.MapTestSuiteBuilder}.
41
 *
42
 * @author Louis Wasserman
43
 */
44
@GwtCompatible(emulated = true)
45
@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
46
@SuppressWarnings("JUnit4ClassUsedInJUnit3")
47
public class MapMergeTester<K, V> extends AbstractMapTester<K, V> {
48
  @MapFeature.Require(SUPPORTS_PUT)
49
  public void testAbsent() {
50
    assertEquals(
51
        "Map.merge(absent, value, function) should return value",
52
        v3(),
53
        getMap()
54
            .merge(
55
                k3(),
56
                v3(),
57
                (oldV, newV) -> {
58
                  throw new AssertionFailedError(
59
                      "Should not call merge function if key was absent");
60
                }));
61
    expectAdded(e3());
62
  }
63

64
  @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
65
  @CollectionSize.Require(absent = ZERO)
66
  public void testMappedToNull() {
67
    initMapWithNullValue();
68
    assertEquals(
69
        "Map.merge(keyMappedToNull, value, function) should return value",
70
        v3(),
71
        getMap()
72
            .merge(
73
                getKeyForNullValue(),
74
                v3(),
75
                (oldV, newV) -> {
76
                  throw new AssertionFailedError(
77
                      "Should not call merge function if key was mapped to null");
78
                }));
79
    expectReplacement(entry(getKeyForNullValue(), v3()));
80
  }
81

82
  @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
83
  public void testMergeAbsentNullKey() {
84
    assertEquals(
85
        "Map.merge(null, value, function) should return value",
86
        v3(),
87
        getMap()
88
            .merge(
89
                null,
90
                v3(),
91
                (oldV, newV) -> {
92
                  throw new AssertionFailedError(
93
                      "Should not call merge function if key was absent");
94
                }));
95
    expectAdded(entry(null, v3()));
96
  }
97

98
  @MapFeature.Require(SUPPORTS_PUT)
99
  @CollectionSize.Require(absent = ZERO)
100
  public void testMergePresent() {
101
    assertEquals(
102
        "Map.merge(present, value, function) should return function result",
103
        v4(),
104
        getMap()
105
            .merge(
106
                k0(),
107
                v3(),
108
                (oldV, newV) -> {
109
                  assertEquals(v0(), oldV);
110
                  assertEquals(v3(), newV);
111
                  return v4();
112
                }));
113
    expectReplacement(entry(k0(), v4()));
114
  }
115

116
  private static class ExpectedException extends RuntimeException {}
117

118
  @MapFeature.Require(SUPPORTS_PUT)
119
  @CollectionSize.Require(absent = ZERO)
120
  public void testMergeFunctionThrows() {
121
    try {
122
      getMap()
123
          .merge(
124
              k0(),
125
              v3(),
126
              (oldV, newV) -> {
127
                assertEquals(v0(), oldV);
128
                assertEquals(v3(), newV);
129
                throw new ExpectedException();
130
              });
131
      fail("Expected ExpectedException");
132
    } catch (ExpectedException expected) {
133
    }
134
    expectUnchanged();
135
  }
136

137
  @MapFeature.Require(SUPPORTS_REMOVE)
138
  @CollectionSize.Require(absent = ZERO)
139
  public void testMergePresentToNull() {
140
    assertNull(
141
        "Map.merge(present, value, functionReturningNull) should return null",
142
        getMap()
143
            .merge(
144
                k0(),
145
                v3(),
146
                (oldV, newV) -> {
147
                  assertEquals(v0(), oldV);
148
                  assertEquals(v3(), newV);
149
                  return null;
150
                }));
151
    expectMissing(e0());
152
  }
153

154
  public void testMergeNullValue() {
155
    try {
156
      getMap()
157
          .merge(
158
              k0(),
159
              null,
160
              (oldV, newV) -> {
161
                throw new AssertionFailedError("Should not call merge function if value was null");
162
              });
163
      fail("Expected NullPointerException or UnsupportedOperationException");
164
    } catch (NullPointerException | UnsupportedOperationException expected) {
165
    }
166
  }
167

168
  public void testMergeNullFunction() {
169
    try {
170
      getMap().merge(k0(), v3(), null);
171
      fail("Expected NullPointerException or UnsupportedOperationException");
172
    } catch (NullPointerException | UnsupportedOperationException expected) {
173
    }
174
  }
175

176
  @MapFeature.Require(absent = SUPPORTS_PUT)
177
  public void testMergeUnsupported() {
178
    try {
179
      getMap()
180
          .merge(
181
              k3(),
182
              v3(),
183
              (oldV, newV) -> {
184
                throw new AssertionFailedError();
185
              });
186
      fail("Expected UnsupportedOperationException");
187
    } catch (UnsupportedOperationException expected) {
188
    }
189
  }
190

191
  /**
192
   * Returns the {@link Method} instance for {@link #testMergeNullValue()} so that tests of {@link
193
   * Hashtable} can suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()}.
194
   */
195
  @J2ktIncompatible
196
  @GwtIncompatible // reflection
197
  public static Method getMergeNullValueMethod() {
198
    return Helpers.getMethod(MapMergeTester.class, "testMergeNullValue");
199
  }
200
}
201

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

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

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

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