Java

Форк
0
/
MapComputeIfAbsentTester.java 
206 строк · 6.5 Кб
1
/*
2
 * Copyright (C) 2015 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

24
import com.google.common.annotations.GwtCompatible;
25
import com.google.common.collect.testing.AbstractMapTester;
26
import com.google.common.collect.testing.features.CollectionSize;
27
import com.google.common.collect.testing.features.MapFeature;
28
import java.util.Map;
29
import junit.framework.AssertionFailedError;
30
import org.junit.Ignore;
31

32
/**
33
 * A generic JUnit test which tests {@link Map#computeIfAbsent}. Can't be invoked directly; please
34
 * see {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
35
 *
36
 * @author Louis Wasserman
37
 */
38
@GwtCompatible
39
@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
40
@SuppressWarnings("JUnit4ClassUsedInJUnit3")
41
public class MapComputeIfAbsentTester<K, V> extends AbstractMapTester<K, V> {
42

43
  @MapFeature.Require(SUPPORTS_PUT)
44
  public void testComputeIfAbsent_supportedAbsent() {
45
    assertEquals(
46
        "computeIfAbsent(notPresent, function) should return new value",
47
        v3(),
48
        getMap()
49
            .computeIfAbsent(
50
                k3(),
51
                k -> {
52
                  assertEquals(k3(), k);
53
                  return v3();
54
                }));
55
    expectAdded(e3());
56
  }
57

58
  @MapFeature.Require(SUPPORTS_PUT)
59
  @CollectionSize.Require(absent = ZERO)
60
  public void testComputeIfAbsent_supportedPresent() {
61
    assertEquals(
62
        "computeIfAbsent(present, function) should return existing value",
63
        v0(),
64
        getMap()
65
            .computeIfAbsent(
66
                k0(),
67
                k -> {
68
                  throw new AssertionFailedError();
69
                }));
70
    expectUnchanged();
71
  }
72

73
  @MapFeature.Require(SUPPORTS_PUT)
74
  public void testComputeIfAbsent_functionReturnsNullNotInserted() {
75
    assertNull(
76
        "computeIfAbsent(absent, returnsNull) should return null",
77
        getMap()
78
            .computeIfAbsent(
79
                k3(),
80
                k -> {
81
                  assertEquals(k3(), k);
82
                  return null;
83
                }));
84
    expectUnchanged();
85
  }
86

87
  @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
88
  @CollectionSize.Require(absent = ZERO)
89
  public void testComputeIfAbsent_nullTreatedAsAbsent() {
90
    initMapWithNullValue();
91
    assertEquals(
92
        "computeIfAbsent(presentAssignedToNull, function) should return newValue",
93
        getValueForNullKey(),
94
        getMap()
95
            .computeIfAbsent(
96
                getKeyForNullValue(),
97
                k -> {
98
                  assertEquals(getKeyForNullValue(), k);
99
                  return getValueForNullKey();
100
                }));
101
    expectReplacement(entry(getKeyForNullValue(), getValueForNullKey()));
102
  }
103

104
  @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
105
  public void testComputeIfAbsent_nullKeySupported() {
106
    getMap()
107
        .computeIfAbsent(
108
            null,
109
            k -> {
110
              assertNull(k);
111
              return v3();
112
            });
113
    expectAdded(entry(null, v3()));
114
  }
115

116
  static class ExpectedException extends RuntimeException {}
117

118
  @MapFeature.Require(SUPPORTS_PUT)
119
  public void testComputeIfAbsent_functionThrows() {
120
    try {
121
      getMap()
122
          .computeIfAbsent(
123
              k3(),
124
              k -> {
125
                assertEquals(k3(), k);
126
                throw new ExpectedException();
127
              });
128
      fail("Expected ExpectedException");
129
    } catch (ExpectedException expected) {
130
    }
131
    expectUnchanged();
132
  }
133

134
  @MapFeature.Require(absent = SUPPORTS_PUT)
135
  public void testComputeIfAbsent_unsupportedAbsent() {
136
    try {
137
      getMap()
138
          .computeIfAbsent(
139
              k3(),
140
              k -> {
141
                // allowed to be called
142
                assertEquals(k3(), k);
143
                return v3();
144
              });
145
      fail("computeIfAbsent(notPresent, function) should throw");
146
    } catch (UnsupportedOperationException expected) {
147
    }
148
    expectUnchanged();
149
  }
150

151
  @MapFeature.Require(absent = SUPPORTS_PUT)
152
  @CollectionSize.Require(absent = ZERO)
153
  public void testComputeIfAbsent_unsupportedPresentExistingValue() {
154
    try {
155
      assertEquals(
156
          "computeIfAbsent(present, returnsCurrentValue) should return present or throw",
157
          v0(),
158
          getMap()
159
              .computeIfAbsent(
160
                  k0(),
161
                  k -> {
162
                    assertEquals(k0(), k);
163
                    return v0();
164
                  }));
165
    } catch (UnsupportedOperationException tolerated) {
166
    }
167
    expectUnchanged();
168
  }
169

170
  @MapFeature.Require(absent = SUPPORTS_PUT)
171
  @CollectionSize.Require(absent = ZERO)
172
  public void testComputeIfAbsent_unsupportedPresentDifferentValue() {
173
    try {
174
      assertEquals(
175
          "computeIfAbsent(present, returnsDifferentValue) should return present or throw",
176
          v0(),
177
          getMap()
178
              .computeIfAbsent(
179
                  k0(),
180
                  k -> {
181
                    assertEquals(k0(), k);
182
                    return v3();
183
                  }));
184
    } catch (UnsupportedOperationException tolerated) {
185
    }
186
    expectUnchanged();
187
  }
188

189
  @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS)
190
  public void testComputeIfAbsent_nullKeyUnsupported() {
191
    try {
192
      getMap()
193
          .computeIfAbsent(
194
              null,
195
              k -> {
196
                assertNull(k);
197
                return v3();
198
              });
199
      fail("computeIfAbsent(null, function) should throw");
200
    } catch (NullPointerException expected) {
201
    }
202
    expectUnchanged();
203
    expectNullKeyMissingWhenNullKeysUnsupported(
204
        "Should not contain null key after unsupported computeIfAbsent(null, function)");
205
  }
206
}
207

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

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

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

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