的 1.单元测试 强>
如果您的目的是对公共方法进行单元测试 fallbackPersons 通过嘲弄 CacheManager ,我强烈建议通过使用构造函数注入来更改注入cacheManager bean的样式:
fallbackPersons
CacheManager
import javax.cache.Cache; import javax.cache.CacheManager; @Service public class PersonsService { private final CacheManager cacheManager; @Autowired public PersonsService(@Qualifier(value = "cacheManager") CacheManager cacheManager) { this.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 并编写其行为,您将不需要引导Spring上下文(应用@Autowired),或使用Powermock库来访问私有属性。
单元测试示例:
public class PersonsServiceTest { @Test public void fallbackPersonsWithEmptyCache() { CacheManager cacheManager = Mockito.mock(CacheManager.class); Mockito.when(cacheManager.getCache(Matchers.anyString())) .thenReturn(Collections.emptyList()); PersonsService service = new PersonsService(cacheManager); List<Person> persons = service.fallbackPersons(); Assert.assertNotNull(persons); Assert.assertTrue(persons.isEmpty()); } }
的 2.集成测试 强>
如果您真的想用Spring中的真实缓存管理器实现来测试您的服务,那么您应该查看如何使用的示例 AbstractJUnit4SpringContextTests 要么 AbstractTestNGSpringContextTests Spring Framework提供的类。它们将允许您初始化真正的Spring上下文并注入真实的CacheManager实现,如EhCahce等。
AbstractJUnit4SpringContextTests
AbstractTestNGSpringContextTests
解决我的问题的正确方法。
@ActiveProfiles("test") @RunWith(MockitoJUnitRunner.class) @Slf4j public class CacheTest { @Spy @InjectMocks PersonService personService; @Mock private CacheManager cacheManager; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void fallbackMCCsWithNonEmptyCache() { List<Person> persons = Collections.singletonList(new Person()); Iterator<Cache.Entry <Object, Object>> cacheIterator = Mockito.mock(Iterator.class); Cache <Object, Object> cache = Mockito.mock(Cache.class); Cache.Entry <Object, Object> entry = Mockito.mock(Cache.Entry.class); Mockito.when(cacheManager.getCache(Mockito.anyString())) .thenReturn(cache); Mockito.when(cache.iterator()).thenReturn(cacheIterator); List<Person> personList = personService.fallbackPersons(); Assert.assertNotNull(personList); Assert.assertTrue(personList.isEmpty()); } }