[英]Junit for Spring Cache Manager
我在應用程序中使用Spring緩存層,在編寫單元測試以使用Mockito測試Spring緩存層時遇到了一個問題。
請針對我的問題參考以下代碼:
服務層:
public CustomerServiceImpl implements CustomerService {
@Autowired
private CacheManager cacheManager;
@Autowired
private CustomerRepository customerRepository;//Repository is simple JPA repository interface which contains findByCustomerName()
@Override
@CachePut(value = "#customer", key = "#customer.customerName")
public Customer insertOrUpdate(Customer customer) {
return customerRepository.save(customer);
}
@Cacheable(value="customersCache", key = "#customerName")
public Customer findByCustomerName(String customerName) {
Customer customer = customerRepository.findByCustomerName(customerName);
return customer;
}
}
用於服務層的JUnit測試代碼:
@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomerServiceImplTest.class)
public class CustomerServiceImplTest {
@Spy
CacheManager cacheManager = new ConcurrentMapCacheManager("customersCache");
@Mock
CustomerRepository CustomerRepository;
@InjectMocks
CustomerServiceImpl customerServiceImpl = new CustomerServiceImpl();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCacheForFindByCustomerName() {
Customer customer1 = new Customer();
customer1.setId("1");
customer1.setName("John");
Customer customer2 = new Customer();
customer2.setId("2");
customer2.setName("Sara");
//this should save to cache
Mockito.when(CustomerRepository.save(customer1))
.thenReturn(customer1);
customerServiceImpl.insertOrUpdate(customer1);
//Now it should retreive from cache, but not able to
Mockito.when(CustomerRepository.findByCustomerName(Mockito.any(String.class)))
.thenReturn(customer1, customer2);
Customer result = customerServiceImpl.findByCustomerName("John");
assertThat(result, is(customer1));
result = customerServiceImpl.findByCustomerName("John");
assertThat(result, is(customer1));
}
}
例外:
我得到一個“ java.lang.AssertionError:
”,因為緩存層不起作用,並且調用已傳遞給存儲庫對象(兩次),該對象已返回上面的“ customer2”模擬對象,即,存儲庫方法已被調用兩次通過服務層獲取相同的密鑰。
另外,請注意,我正在使用“ Mockito”框架進行測試。
我已經嘗試過在Spring緩存上使用google進行單元測試,並且還引用了以下URL,該URL幾乎使用相同的概念,但不適用於我的上述代碼。
如何在Spring數據存儲庫上測試Spring的聲明式緩存支持?
您能幫忙解決以上例外情況嗎?
Spring Cache Manager依靠Spring管理應用程序。 使用PowerMockRunner
無法獲得它,您需要使用SpringJUnit4Runner
。 您仍然可以通過編程方式使用PowerMock或Mockito,但不能作為Runner使用。
通常,您會將單元測試轉換為Spring風格的集成測試,如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringTest {
@Configuration
@EnableCaching
static class SpringConfig{
@Bean
public CustomerService customerService(){
return new CustomerServiceImpl(customerRepository());
}
@Bean
public CustomerRepository customerRepository(){
return Mockito.mock(CustomerRepository.class);
}
}
@Autowired
CustomerService customerService; // this will contain a proper managed cache
@Autowired
CustomerRepository customerRepository; // this is a mockito mock you can fine-tune
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.