英文:
Testing a Vaadin view in a unit test yields VaadinService.getCurrent()" is null
问题
抱歉,你的输入包含代码部分,根据你的要求,我只提供翻译,不提供代码。以下是翻译好的部分:
"我正在尝试测试一个 Vaadin 视图。其中一个 Component
是一个包含 ApexCharts
的 div。
当我测试页面的另一个组件(某个 Grid)时,我收到以下错误:
java.lang.NullPointerException: 无法调用 "com.vaadin.flow.server.VaadinService.getDeploymentConfiguration()",因为 "com.vaadin.flow.server.VaadinService.getCurrent()" 的返回值为 null
关于 ApexChartsBuilder.get()...build()
这一行的原因是什么?"
英文:
I'm trying to test a Vaadin view. One of the Component
s is a div containing an ApexCharts
.
While I'm testing another component of the page (some Grid) I'm getting the following error:
> java.lang.NullPointerException: Cannot invoke "com.vaadin.flow.server.VaadinService.getDeploymentConfiguration()" because the return value of "com.vaadin.flow.server.VaadinService.getCurrent()" is null
For the line ApexChartsBuilder.get()...build()
Why?
答案1
得分: 1
这是预期的,当视图在隔离环境中实例化时,框架的内部类,如UI、VaadinSession、VaadinService等,不会自动实例化。这意味着VaadinService.getCurrent()、UI.getCurrent()将返回null,因为线程本地变量未被设置。
如果您希望对视图进行单元测试,您需要模拟Vaadin的内部类。对于简单情况来说,这并不是特别困难,但在更复杂的情况下可能会变得很深。
您可以在这里找到一个使用基本Vaadin模拟的简单组件UI单元测试:
https://github.com/TatuLund/bean-table/blob/nextlts/src/test/java/org/vaadin/tatu/BeanTableTest.java
在Vaadin 23中,商业TestBench附加组件附带了UI单元测试库,基本包含了这些模拟。对于Vaadin 14,您可以尝试使用Karibu,它基本上是相同的。
您可以在这里找到一个视图的UI单元测试示例:
https://github.com/TatuLund/TwinColSelect/blob/nextlts/src/test/java/org/vaadin/tatu/ViewTest.java
英文:
This is as expected as when view is instantiated in isolation, the Framework's internal classes such as UI, VaadinSession, VaadinService etc. are not automatically being instantiated. That will mean that VaadinService.getCurrent(), UI.getCurrent() will return null, as the thread locals has not been set.
If you wish to do unit testing on your views, you need to have Vaadin's internal classes mocked. For simple cases it is not super hard to do, but in more complex cases can be a deep rabit hole.
You can find a simple component UI unit test with basic Vaadin mocks here:
https://github.com/TatuLund/bean-table/blob/nextlts/src/test/java/org/vaadin/tatu/BeanTableTest.java
In Vaadin 23, the commercial TestBench add-on comes with UI Unit Test library, which is essentially containing these mocks. With Vaadin 14 you could try to use Karibu, which is essentially the same.
You can find example of UI Unit Test of a view here
https://github.com/TatuLund/TwinColSelect/blob/nextlts/src/test/java/org/vaadin/tatu/ViewTest.java
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论