sebastyn.dietrich
sebastyn.dietrich

Reputation: 13

junit test is failing with exception

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.

Upvotes: 1

Views: 1173

Answers (1)

deepakchethan
deepakchethan

Reputation: 5600

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

Upvotes: 1

Related Questions