[英]Mocking chained method calls using mockito?
我需要模擬一下:
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)
我也看到了下面的相同問題:
模擬或存根以進行鏈接呼叫
有人可以指出我所缺少的嗎?
謝謝,
莫希特
我認為問題在於您正在嘗試在客戶端瀏覽器環境之外執行GWT代碼。 GWT旨在轉換為JavaScript並在瀏覽器上運行。 我不確定它是否可以正常工作。
我注意到NativeEvent
第137 NativeEvent
似乎是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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.