0

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);
  }
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Lesiak Nov 01 '22 at 22:50
  • @lesiak the question here is builder method is of the type abstract , that method is throwing NPE. do i have to mock it ? – Aishwarya Patil Nov 02 '22 at 14:47
  • Please post full stack trace – Lesiak Nov 02 '22 at 16:15
  • What value does `builder` have? It is a mock? What value does `builder()` return? (but very likely everything is already answered in the link posted by Lesiak "what is a NPE and how to fix") – knittl Nov 04 '22 at 17:44

2 Answers2

0

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

  • I tried mocking buckets.builder first and then buckets.builder.build () that helped me to get the unit test working. I have a proxy manager bean initialized by JcacheProxyManager. thanks for your help! – Aishwarya Patil Nov 17 '22 at 21:57
0

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);

}