Unit test proxyManager

326 Views Asked by At

I need to unit test this code, but i have been seeing null pointer exceptions at buckets.builder().

import io.github.bucket4j.distributed.proxy.ProxyManager;


private ProxyManager buckets;

 public Bucket resolveBucket(String key) {
    Supplier<BucketConfiguration> configSupplier = getConfigSupplierForUser();
    return buckets.builder().build(key, configSupplier);
  }
2

There are 2 best solutions below

1
On

buckets is null, because you did not set any value to this field. You need to initialize this field before calling any method.

0
On

I tried mocking buckets.builder first and then buckets.builder.build () that helped me to get the unit test to work. I have a proxy manager bean initialized by JcacheProxyManager.

 @InjectMocks private RateLimitingService rateLimitingService;

  @Mock RemoteBucketBuilder<String> remoteBucketBuilder;

  @Mock ProxyManager<String> buckets;

  @Test
  void shouldGetBucketsForThePassedKey() throws NoSuchAlgorithmException {

when(buckets.builder()).thenReturn(remoteBucketBuilder);
when(remoteBucketBuilder.build(
        anyString(), ArgumentMatchers.<Supplier<BucketConfiguration>>any()))
    .thenReturn(mock(BucketProxy.class));
Bucket bucket = rateLimitingService.resolveBucket("1", "1", "1");
assertNotNull(bucket);

}