我需要模拟这个:
void handleCellPreview(CellPreviewEvent<List<String>> event) {
Element cellElement = event.getNativeEvent().getEventTarget().cast();
}
我正在这样做:
CellPreviewEvent<List<String>> cellPreviewEvent = Mockito.mock(
CellPreviewEvent.class, Mockito.RETURNS_DEEP_STUBS);
Element cellElement = Mockito.mock(Element.class, Mockito.RETURNS_DEEP_STUBS);
EventTarget eventTarget = Mockito.mock(EventTarget.class);
Mockito.when(cellPreviewEvent.getNativeEvent().getEventTarget().cast()).thenReturn(cellElement);
我会得到以下错误:
testHandleCellPreview(client.view.MyViewTest)java.lang.NullPointerException
at com.google.gwt.dom.client.NativeEvent.getEventTarget(NativeEvent.java:137)
atclient.view.MyViewTest.testHandleCellPreview(MyViewTest.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
我也看到了下面的同样问题:
模拟或存根用于链式电话
有人可以指出我缺少的东西吗?
谢谢,
Mohit
我认为问题是您正在尝试在客户端浏览器环境之外执行GWT代码。GWT设计为转换为JavaScript并在浏览器上运行。我不确定它是否可以使用。
我注意到NativeEvent
的第137行似乎是DomImpl.impl.eventGetTarget
。这使我相信DomImpl.impl
是null
。
我通过查看代码找到了以下内容:
45 public static <T> T create(Class<?> classLiteral) {
46 if (sGWTBridge == null) {
47 /*
48 * In Production Mode, the compiler directly replaces calls to this method
49 * with a new Object() type expression of the correct rebound type.
50 */
51 throw new UnsupportedOperationException(
52 "ERROR: GWT.create() is only usable in client code! It cannot be called, "
53 + "for example, from server code. If you are running a unit test, "
54 + "check that your test case extends GWTTestCase and that GWT.create() "
55 + "is not called from within an initializer or constructor.");
56 } else {
57 return sGWTBridge.<T> create(classLiteral);
58 }
59 }
您是否扩展了GWTTestCase
您需要在父实体中再次设置模拟对象。因此,在运行 - 时间,它使用模拟的对象。
cellPreviewEvent.setCellElement(cellElement);
cellPreviewEvent.setEventTarget(eventTarget);
完整的代码看起来像:
CellPreviewEvent<List<String>> cellPreviewEvent = Mockito.mock(
CellPreviewEvent.class, Mockito.RETURNS_DEEP_STUBS);
Element cellElement = Mockito.mock(Element.class, Mockito.RETURNS_DEEP_STUBS);
EventTarget eventTarget = Mockito.mock(EventTarget.class);
cellPreviewEvent.setCellElement(cellElement);
cellPreviewEvent.setEventTarget(eventTarget);
Mockito.when(cellPreviewEvent.getNativeEvent().getEventTarget().cast()).thenReturn(cellElement);