仪表式计数器测试案件失败
我已经通过注入 meterRegistry
并增加了计数,在我的服务中实现了千分尺Prometheus计数器,但我也写了一个测试用例,但是当我运行测试用例时,我会得到:
“ java.lang.nullpointerexception:无法调用 “ io.micrometer.core.instrument.MeterRegistry.Counter(String, string [])“因为“ this.meterregistry”为null”。
服务文件:
@Autowired
private MeterRegistry meterRegistry;
public void counterIncrement() {
meterRegistry.counter("test_count").increment();
}
测试案例文件:
@MockBean
private MeterRegistry registry;
@Test
void testCounter() {
// invoking counterIncrement();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 SimpleSemeterRegistry
You can test metrics without Mockito using SimpleMeterRegistry
您如何创建正在测试的课程?
由于
注册表
永远不会实例化,因此您如何设置测试的方式似乎有所了解。检查您是否以正确的方式使用
@mockbean
。这将在应用程序上下文中替换BEAN,如果您在测试中不旋转弹簧上下文,则它将行不通。请参阅此此帖子以获取更多信息。另一种方法是使用
@mock
并将注册表注入构造函数,例如: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 in 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:根据您使用的Junit版本,您需要将注释添加到测试类中。 junit 5:
@extendwith(mockitoextension.class)
或for junit 4:@runwith(MockitoJunitRunner.Class)
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)
根据测试和服务的不同,有几种处理缺失的计量记录的方法。
@BeForeEach
播种,如@Checketts 在评论中。@component
,以及工厂的一些公共Getter。我偏爱解决方案3,但会在适当时使用解决方案1。我添加了解决方案4和5仅仅是因为可能还有一些其他原因和特殊情况使这些解决方案成为一个不错的选择。如果是这样,我更喜欢4比5。
Depending on the test and the service there are several ways to deal with the missing MeterRegistry.
@BeforeEach
as suggested by @checketts in the comments.@Component
with an autowired MeterRegistry and some public getter for the factory.I favour solution 3 but would use solution 1 whenever appropriate. I've added solutions 4 and 5 just because there might be some additional reasons and special cases that make these solutions a good choice. If so, I prefer 4 over 5.