我需要嘲笑这个:
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)
我也见过,同样的问题如下:
mock or stub for chained call
任何人都可以指出我错过了什么?
谢谢,
莫希特
答案 0 :(得分:1)
我认为问题在于您尝试在客户端浏览器环境之外执行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
答案 1 :(得分:-1)
您需要在父实体中再次设置模拟对象。因此,在运行时,它使用模拟对象。
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);