I have implemented micro-meter Prometheus counter in my service by injecting MeterRegistry and incrementing the count as shown below , and I have written a test case as well , but when I am running the test case , I am getting
"java.lang.NullPointerException: Cannot invoke "io.micrometer.core.instrument.MeterRegistry.counter(String, String[])" because "this.meterRegistry" is null".
Please can someone help
Service file:
@Autowired
private MeterRegistry meterRegistry;
public void counterIncrement()
{
meterRegistry.counter("test_count").increment();
}
Test case file:
@MockBean
private MeterRegistry registry;
@Test
void testCounter()
{
// invoking counterIncrement();
}
CodePudding user response:
Depending on which junit version you are using you need to add the annotation to your test class. Junit 5: @ExtendWith(MockitoExtension.class)
or for Junit 4: @RunWith(MockitoJUnitRunner.class)
CodePudding user response:
How do you create your class under test?
Since the registry
is never instantiated, something seems up with how you setup your test.
Check that you are using the @MockBean
in the correct way. This will replace the bean in the application context and if you do not spin up a spring context i your test, it will not work. See this post for more info
A different approach would be to use @Mock
and inject the registry in the constructor, example:
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@Mock
private MeterRegistry registry;
private MyService myService;
@BeforeEach
void setup() {
myService = new MyService(registry);
}
@Test
void testCounter() {
var counter = mock(Counter.class);
given(registry.counter(any(String.class))).willReturn(counter);
myService.counterIncrement();
}