Call the value adapter during NamedContributorsMapAdapter construction

Update `NamedContributorsMapAdapter` so that the adapter function is
called only once per entry. Prior to this commit, the adapter was called
dynamically which made `CompositeHealthContributor` behave differently
from a regular `HealthContributor`.

See gh-31676
This commit is contained in:
Guirong Hu
2022-07-11 18:11:09 +08:00
committed by Phillip Webb
parent 5243cb8369
commit c530f12cc3
2 changed files with 44 additions and 16 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
@@ -92,6 +93,22 @@ class NamedContributorsMapAdapterTests {
assertThat(adapter.getContributor("two")).isEqualTo("owt");
}
@Test
void eachValueAdapterShouldBeCalledOnlyOnce() {
Map<String, String> map = new LinkedHashMap<>();
map.put("one", "one");
map.put("two", "two");
int callCount = map.size();
AtomicInteger counter = new AtomicInteger(0);
TestNamedContributorsMapAdapter<String> adapter = new TestNamedContributorsMapAdapter<>(map,
(name) -> count(name, counter));
assertThat(adapter.getContributor("one")).isEqualTo("eno");
assertThat(counter.get()).isEqualTo(callCount);
assertThat(adapter.getContributor("two")).isEqualTo("owt");
assertThat(counter.get()).isEqualTo(callCount);
}
@Test
void getContributorWhenNotInMapReturnsNull() {
TestNamedContributorsMapAdapter<String> adapter = createAdapter();
@@ -106,6 +123,11 @@ class NamedContributorsMapAdapterTests {
return adapter;
}
private String count(CharSequence charSequence, AtomicInteger counter) {
counter.incrementAndGet();
return reverse(charSequence);
}
private String reverse(CharSequence charSequence) {
return new StringBuilder(charSequence).reverse().toString();
}