guava

Форк
0
199 строк · 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
public class MapMergeTester<K, V> extends AbstractMapTester<K, V> {
47
  @MapFeature.Require(SUPPORTS_PUT)
48
  public void testAbsent() {
49
    assertEquals(
50
        "Map.merge(absent, value, function) should return value",
51
        v3(),
52
        getMap()
53
            .merge(
54
                k3(),
55
                v3(),
56
                (oldV, newV) -> {
57
                  throw new AssertionFailedError(
58
                      "Should not call merge function if key was absent");
59
                }));
60
    expectAdded(e3());
61
  }
62

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

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

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

115
  private static class ExpectedException extends RuntimeException {}
116

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

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

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

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

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

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

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

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

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

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