清单 3. 重构的 onModuleLoad 方法委托给更易于测试的方法
public void onModuleLoad() {
HorizontalPanel inputPanel = new HorizontalPanel();
inputPanel.setStyleName("disco-input-panel");
inputPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
Label lbl = this.getLabel();
inputPanel.add(lbl);
TextBox txBox = this.getTextBox();
inputPanel.add(txBox);
Button btn = this.getButton();
btn.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
submitWord();
}
});
inputPanel.add(btn);
inputPanel.setCellVerticalAlignment(btn,
HasVerticalAlignment.ALIGN_BOTTOM);
if(RootPanel.get("input-container") != null) {
RootPanel.get("input-container").add(inputPanel);
}
Label output = this.getOutputLabel();
if(RootPanel.get("output-container") != null) {
RootPanel.get("output-container").add(output);
}
}
如清单 3 所示,我已经把 onModuleLoad() 的定义获取逻辑委托给 submitWord 方法,如清单 4 定义:
清单 4. 我的 Ajax 应用程序的实质!
protected void submitWord() {
String word = this.getTextBox().getText().trim();
this.getDefinition(word);
}
protected void getDefinition(String word) {
WordServiceAsync instance = WordService.Util.getInstance();
try {
instance.getDefinition(word, new AsyncCallback() {
public void onFailure(Throwable error) {
Window.alert("Error occurred:" + error.toString());
}
public void onSuccess(Object retValue) {
getOutputLabel().setText(retValue.toString());
}
});
}catch(Exception e) {
e.printStackTrace();
}
}
文章来源于领测软件测试网 https://www.ltesting.net/