1

I working on junit to test my Metrics class. When the test runs I get no exceptions but the test doesn't success. I have tried to find all different issues but didn't find any. Here are the codes for it.

public class MetricsTest {
  private MetricsHelper metricHelper;
  private MeterRegistry registry;
  private Timer timer;
    
  @Before
  public void setup(){
    registry = spy(mock(MeterRegistry.class));
    when(registry.timer(any(), any(Tags.class))).thenReturn(timer);
    metricHelper = new MetricHelper(registry);
  }

  @Test
  public void testSubmitSuccessWithoutContext() throws Exception {
    metricHelper.submitTimer(metric, 1L, TimeUnit.SECONDS);
    verify(registry, times(1)).timer(
        KEY_PREFIX_TIMER_METRIC + metric.toLowerCase());
  }
}

I get exception java.lang.NullPointerException at com.company.metrics.MetricsHelper.submitTimer(MetricsHelper.java:39). Please help me with solution.

1 Answer 1

1

Looks to me that you are not initializing the Timer object which might be causing this NPE. Please try initialising as follows:

  private MetricsHelper metricHelper;
  private MeterRegistry registry;
  private Timer timer;
    
  @Before
  public void setup(){
    registry = spy(mock(MeterRegistry.class));
    timer = mock(Timer.class);
    when(registry.timer(any(), any(Tags.class))).thenReturn(timer);
    metricHelper = new MetricHelper(registry);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.