gpt4 book ai didi

java - 使用 for 循环从 CacheManger 检索数据的方法的单元测试

转载 作者:行者123 更新时间:2023-12-02 01:52:30 27 4
gpt4 key购买 nike

我有一种方法,可以从下一个 webapi 检索人员并将其存储在缓存中,并且我想从缓存管理器中获取相同的缓存数据。我在为此方法编写单元测试时遇到困难。非常感谢任何帮助

import javax.cache.Cache;
import javax.cache.CacheManager;

@Autowired
@Qualifier(value = "cacheManager")
private CacheManager cacheManager;

*public List<Person> fallbackPersons() {
List<Person> data = new ArrayList<>();
for (Cache.Entry<Object, Object> entry :cacheManager.getCache("person"){
data = (List<Person>) entry.getValue();
}
return data;
}*

最佳答案

您可以模拟 CacheManager,对其进行 stub 并验证结果,如下所示:

    @RunWith(MockitoJUnitRunner.class)
public class PersonsServiceTest {

@Mock
private CacheManager cacheManager;

@InjectMocks
PersonsService service = new PersonsService();

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}

@Test
public void fallbackPersonsWithNonEmptyCache() {
List<Person> persons = Collections.singletonList(new Person()); // create person object as your Person class definition
// mock cache entry
Cache.Entry <Object, Object> entry = Mockito.mock(Cache.Entry.class);

// do stubbing
Mockito.when(entry.getValue()).thenReturn(persons);
Mockito.when(cacheManager.getCache(Matchers.anyString()))
.thenReturn(entry);

// execute
List<Person> persons = service.fallbackPersons();

// verify
Assert.assertNotNull(persons);
Assert.assertFalse(persons.isEmpty());
}
}

关于java - 使用 for 循环从 CacheManger 检索数据的方法的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com