如何对可缓存方法进行单元测试

时间:2019-07-04 16:44:53

标签: java spring caching

我正在使用Spring Cache。 我有一个Spring控制器,作为负责该GET请求的方法的一部分,我用@Cacheable(value = "customer", key = "#accountId")对其进行了注释。在该方法中,它调用API并执行一些业务逻辑,然后返回DTO。有了适当的缓存注释,我期望在此代码的第一次执行时可以正常运行,但以后再进行任何后续调用,它将从缓存中获取结果。是正确的吗?

我正在编写一个单元测试,以验证该API是否曾经被调用过,尽管模拟了向该控制器发送的多个请求。但是问题在于它会多次调用API,而不是调用缓存。

单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebMvcTest(controllers = CustomerController.class, secure = false)
public class CustomerControllerTest {

private static final String ACCOUNT_ID = "1111";

   @MockBean
   private CustomerService customerService;
   @MockBean
   private CustomerPortAPI customerPortAPI;
   @Autowired
   MockMvc mockMvc;

   @Before
   public void setUp(){
      when(customerService.getStatus(any())).thenReturn("test");
      when(customerPortAPI.getAccount(any())).thenReturn(Account.builder().build());
   }
   @Test
public void shouldReturnCustomerDTOt() throws Exception {
  when(customerService.Status(any())).thenReturn("test");
  when(customerPortAPI.getAccount(ACCOUNT_ID)).thenReturn(Account.builder().accountId(ACCOUNT_ID).build());

  mockMvc.perform(get("/customer/{accountId}/status", ACCOUNT_ID)
     .accept(APPLICATION_JSON))
     .andExpect(status().isOk())
     .andExpect(jsonPath("status").value(customer.NOT_REQUIRED.name()));


  mockMvc.perform(get("/customer/{accountId}/status", ACCOUNT_ID)
     .accept(APPLICATION_JSON))
     .andExpect(status().isOk())
     .andExpect(jsonPath("status").value(customer.NOT_REQUIRED.name()));


  verify(customerPorAPI, times(1)).getAccount(ACCOUNT_ID);

}}

控制器方法:

@Cacheable(value = "statusEligibility", key = "#customerId")
@GetMapping
public CustomerStatusDTO getCustomerStatus(@PathVariable String customerId) {

Customer customer = cusomterPort.getAccount(customerId);
Status status = service.getStatus(customer);

if (status.equals(Cons.REQUIRED)) {
 /.../
} else {
 /.../
}

0 个答案:

没有答案
相关问题