我有一种方法,可以从下一个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,对其进行存根并按如下所示验证结果:

    @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());
        }
    }

07-24 09:44
查看更多