Home > Software design >  LoadingCache mocking for JUnit testing
LoadingCache mocking for JUnit testing

Time:06-29

I need to test this method.

public String getTenantName(String tenantId) {
    var tenant = getTenant(tenantId);
    if (tenant == null) {
      throw new TenantNotFoundException(tenantId);
    }

    return tenant.getTenantname();
  }

but I am having problems with mocking the below loading cache

  LoadingCache<String, Tenant> tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
      .expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
        @Override
        public Tenant load(String tenantId) {
          return tenantClient.getTenant(tenantId);
        }
      });

as this is being called by another private method

  private Tenant getTenant(String tenantId) {
    try {
      if (StringUtils.isBlank(tenantId)) {
        return null;
      }
      return tenantCache.get(tenantId);
    } catch (TenantNotFoundException | ExecutionException e) {
      logger.error(tenantId, e);
      throw new TenantNotFoundException(tenantId);
    }
  }

I would really appreciate some help here.

I mocked loading cache @mock LoadingCache<String, Tenant> tenantCache;

and then in my test function I create a tenant object and return that on tenantCache.get() call.

tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
                  .expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
                      @Override
                      public Tenant load(String tenantId) {
                        return tenantClient.getTenant(tenantId);
                      }
                    });
        
        Map<String, Tenant> map = new HashMap<String, Tenant>();
        map.put("test", tenant);
        tenantCache.putAll(map);

also for tenantClient I changed that to return tenant. return tenantClient.getTenant(id) =>> return tenant; as tenantClient is calling another API.

CodePudding user response:

So, LoadingCache appears as a variable inside the service but it is implemented as an anonymous class. Therefore we need to mock LoadingCache and use

when(tenantCache.get(anyString())).thenReturn(new Tenant());
  • Related