unit-testing Wicket input components - wicket

I just wrote my first Wicket component :) It contains a ListView with some Radio input fields. Now I want to unit test if a selected value makes its way to the model.
As WicketTester.newFormTester("myForm") expects a form, I try to create a form on the fly:
public void testDataBinding()
{
Model model = ...
MyRadioComponent myRadioComponent = new MyRadioComponent (...);
Form form = new Form("myForm", ...);
form.add(myRadioComponent);
WicketTester wicketTester = new WicketTester();
wicketTester.startComponentInPage(form);
// FormTester formTester = wicketTester.newFormTester("myForm");
// ...
}
Now wicketTester.startComponentInPage(form) results in:
Failed: Component [myForm] (path = [0:x]) must be applied to a tag of type [form],
not: '<span wicket:id="myForm" id="myForm3">'
Any idea how to fix this and/or how to test such an input component the right way?

OK, in detail the solution now looks like this:
public FormTester createFormTester(Component c) {
final WicketTester wicketTester = new WicketTester();
final FormPage page = new FormPage(c);
wicketTester.startPage(page);
return wicketTester.newFormTester(page.getPathToForm());
}
private static class FormPage extends WebPage implements IMarkupResourceStreamProvider {
private final Form<Void> form;
private final Component c;
private FormPage(final Component c) {
this.c = c;
add(form = new Form<>("form"));
form.add(c);
}
public String getPathToForm() {
return form.getPageRelativePath();
}
#Override
public IResourceStream getMarkupResourceStream(MarkupContainer container, Class<?> containerClass) {
return new StringResourceStream(
"<html><body>"
+ "<form wicket:id='" + form.getId() + "'><span wicket:id='" + c.getId() + "'/></form>"
+ "</body></html>");
}
}

I believe startComponentInPage uses a <span> for its component. Wicket checks that Forms are attached to <form> tags which is why you get this error.
You need to create your own test page with a <form> inside it. See org.apache.wicket.markup.html.form.NumberTextFieldTest for an example of inline markup. Otherwise, create a Form test page class with associated html markup file.

Related

How to signal/notify super-controller of change in sub-controller?

In JavaFX, how do you model the following:
I show a List of Customers in a Scene. On the left side there is a table on the right side (contentPane) the currently select customer's details are shown.
(Relevant part of) Main-Controller:
#jfxf.FXML
protected def newButtonPressed(): Unit =
{
contentPane.getChildren.clear
contentPane.getChildren.add(FXMLLoader.load(GUILoader.load("customers/form.fxml")))
}
There is a Button to add a new Customer. Upon clicking this button instead of opening a Popup, I replace the "details"-part of the scene and add a form there.
Now for this form (designed - like the rest of the GUI - in the SceneBuilder and saved as .fxml) I use another controller.
class Form extends Main with jfxf.Initializable
{
#jfxf.FXML
private var foreNameTextField: jfxsc.TextField = _
#jfxf.FXML
private var lastNameTextField: jfxsc.TextField = _
#jfxf.FXML
private var ageTextField: jfxsc.TextField = _
override def initialize(url: URL, resourceBundle: ResourceBundle): Unit =
{
}
#jfxf.FXML
protected def ok(): Unit =
{
// TODO validation
val newPerson = new Person(-1, foreNameTextField.getText, lastNameTextField.getText, ageTextField.getText.toInt)
// Save to DB
// Close whole form
}
}
When I'm done with filling in a new customer's detail I click on another button (that calls ok()) and save it to a database.
What I want to do now is close the form and replace it with the detail-form.
Something like calling a protected method in the main-controller like:
protected def clearDetails(): Unit =
{
contentPane.getChildren.clear
contentPane.getChildren.add(savedOldDetails)
}
won't work of course. (Will throw a runtime-exception because there is no contentpane in the sub/form-controller (even if I make it protected)
In Qt (C++) I'd use signals/slots and connect them accordingly.
Seems like in JavaFX there is nothing the like. How am I supposed to share such information?
Do I need to create a "super-controller" for the contentPane?
(I don't know Scala, so I'll write this in Java, hope that is ok).
You can define an observable property in the Form controller, and observe it when you load the form from the main controller:
public class Form implements Initializable {
private final ObjectProperty<Person> person = new SimpleObjectProperty<>(null);
public ObjectProperty<Person> personProperty() {
return person ;
}
public final Person getPerson() {
return personProperty().get();
}
public final void setPerson(Person person) {
personProperty().set(person);
}
// ... code you had before...
#FXML
protected void ok() {
Person person = new Person(-1, foreNameTextField.getText(), lastNameTextField.getText(), ageTextField.getText());
// save to DB...
personProperty().set(person);
}
}
Now in your main controller, load the form as follows:
#FXML
protected void newButtonPressed() {
contentPane.getChildren().clear();
FXMLLoader loader = new FXMLLoader(getClass().getResource("customers/form.fxml"));
Parent form = loader.load();
Form formController = loader.getController();
formController.personProperty().addListener((obs, oldPerson, newPerson) {
if (newPerson != null) {
// clear form, etc, e.g.
clearDetails();
}
});
contentPane.getChildren().add(form);
}

How to find out component-path

I use junit to assert the existing of wicket components:
wicketTester.assertComponent("dev1WicketId:dev2WicketId:formWicketId", Form.class);
This works for some forms. For complex structure, it is defficult to find out the path of the form by searching all html files. Is there any method how to find out the path easy?
If you have the component you can call #getPageRelativePath(). E.g.
// Supposing c is a component that has been added to the page.
// Returns the full path to the component relative to the page, e.g., "path:to:label"
String pathToComponent = c.getPageRelativePath();
You can get the children of a markup container by using the visitChildren() method. The following example shows how to get all the Forms from a page.
List<Form> list = new ArrayList<Form<?>>();
Page page = wicketTester.getLastRenderedPage();
for (Form form : page.visitChildren(Form.class)) {
list.add(form);
}
An easy way to get those is to call getDebugSettings().setOutputComponentPath(true); when initializing your application. This will make Wicket to output these paths to the generated HTML as an attribute on every component-bound tag.
It's recommended to only enable this on debug mode, though:
public class WicketApplication extends WebApplication {
#Override
public void init() {
super.init();
if (getConfigurationType() == RuntimeConfigurationType.DEVELOPMENT) {
getDebugSettings().setOutputComponentPath(true);
}
}
}
Extending the RJo's answer.
It seems that the method page.visitChildren(<Class>) is deprecated (Wicket 6), so with an IVisitor it can be :
protected String findPathComponentOnLastRenderedPage(final String idComponent) {
final Page page = wicketTester.getLastRenderedPage();
return page.visitChildren(Component.class, new IVisitor<Component, String>() {
#Override
public void component(final Component component, final IVisit<String> visit) {
if (component.getId().equals(idComponent)) {
visit.stop(component.getPageRelativePath());
}
}
});
}

How to concatenate 2 textboxes in wicket?

So i got these 2 text boxes and I'm trying to concatenate them together and show the result in label. I found an example and did it like in the example but something is wrong. So maybe some one can see what I am doing wrong, because i have just started and don't understand how to do it properly.
public class HomePage extends WebPage {
private String fNumber="Big";
private String sNumber=" text!";
private String sResult=fNumber+sNumber;
public HomePage() {
PropertyModel<String> firstNumber = new PropertyModel<String>(this, "fNumber");
PropertyModel<String> secondNumber = new PropertyModel<String>(this, "sNumber");
add(new Label("message", "HelloWorld!"));
add(new Label("result", sResult));
Form<?> form = new Form("form");
form.add(new TextField<String>("firstNumber", firstNumber));
form.add(new TextField<String>("secondNumber", secondNumber));
add(form);
}
}
soo i have made this
` add(new Label("message", "HelloWorld!"));
add(new Label("result", new Model(numb.getsResult())));
Form<?> form = new Form("form") ;
form.add(new TextField<String>("firstNumber", new Model(numb.setfNumber())));
form.add(new TextField<String>("secondNumber",new Model(numb.setsNumber())));
add(form);`
and i have a class that has 3 string fields and getters and setters and sii that much i have understood last comment explained some things maybe some one know how to fix this.
You need to "recalculate" your result. The Wicket way would be to define a Model for your Label that does the concatenation.
add(new Label("result", new IModel<String>(){
#Override
public void detach() {
// do nothing
}
#Override
public String getObject() {
return fNumber + sNumber;
}
#Override
public void setObject(String object) {
// do nothing
}
}));
Additionally you must use the PropertyModels from the example.
To concatenate two strings I usually use StringBuilder:
PropertyModel firstNumber = new PropertyModel(this,"fNumber");
PropertyModel secondNumber = new PropertyModel(this,"sNumber");
PropertyModel resultNumber = new PropertyModel(this,"sResult");
StringBuilder sResult = new StringBuilder((String) firstNumber.getObject());
sResult.append((String) secondNumber.getObject());
resultNumber.setObject(sResult.toString());
Also, please read the link from biziclop as it should help you significantly.

Wicket - changing panels through a dropdown

I have a dropdown component added on a page. the purpose of this dropdown is to change the type of input form that is rendered. for example, different forms have different required fields, editable fields, etc.
public final class Test extends WebPage
{
CustomPanel currentPanel = new MeRequest("repeater",FormType.MIN);
public Test(PageParameters parameters)
{
add(currentPanel);
DropDownChoice ddc = new DropDownChoice("panel", new PropertyModel(this, "selected"), panels, choiceRenderer);
ddc.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
System.out.println("changed");
currentPanel = new MeRequest("repeater",FormType.PRO);
target.add(currentPanel);
}
});
add(ddc);
}
i've tried various options with limited results. the only real success has been updating the model, but what i really want to do is change how the components behave.
any thoughts on what i'm missing?
1) If you want to replace one panel with another you may just do the following.
First of all, you should output the markup id of the original panel:
currentPanel.setOutputMarkupId(true);
And then in the ajax event handler write something like that:
protected void onUpdate(AjaxRequestTarget target) {
CustomPanel newPanel = new MeRequest("repeater", FormType.PRO);
currentPanel.replaceWith(newPanel);
currentPanel = newPanel;
currentPanel.setOutputMarkupId(true);
target.addComponent(currentPanel);
}
In this case with every change of dropdown choice you add new panel to the page and you remove old panel from the page.
2) But I would proposed a slightly different approach to your problem. You should move the construction logic of your panel to the onBeforeRender() method:
public class MeRequest extends Panel {
private FormType formType;
public MeRequest(String id, FormType formType) {
super(id);
this.formType = formType;
// don't forget to output the markup id of the panel
setOutputMarkupId(true);
// constructor without construction logic
}
protected void onBeforeRender() {
// create form and form components based on value of form type
switch (formType) {
case MIN:
// ...
break;
case PRO:
// ...
break;
}
// add form and form components to panel
addOrReplace(form);
form.add(field1);
form.add(field2);
// ...
super.onBeforeRender();
}
public void setFormType(FormType formType) {
this.formType = formType;
}
}
Then you'll be able to only change type of the panel in the ajax event:
protected void onUpdate(AjaxRequestTarget target) {
currentPanel.setFormType(FormType.PRO);
target.addComponent(currentPanel);
}
Thus we rebuilt the original panel without recreating it.

EXT-GWT (GXT) Display Icon and Text for displayfield in Combobox

Does anyone know how to display an Icon and a Text for the displaying field in ext-gwts combobo? I tried everything.
In the third ComboBox of this example (klick me) there is an icon and the text for the selectable values. This was no problem with the example template. But i want to show the icon and the text for the selected value too. How can i manage this?
I have a Model class for the icon and the text.
public class Language extends DbBaseObjectModel {
private static final long serialVersionUID = 8477520184310335811L;
public Language(String langIcon, String langName) {
setLangIcon(langIcon);
setLangName(langName);
}
public String getLangIcon() {
return get("langIcon");
}
public String getLangName() {
return get("langName");
}
public void setLangIcon(String langIcon) {
set("langIcon", langIcon);
}
public void setLangName(String langName) {
set("langName", langName);
}
}
This is how i initalize the ComboBox. I want to change the displayField "langName".
final ListStore<Language> countries = new ListStore<Language>();
final Language german = new Language("de_DE", "Deutsch");
final Language english = new Language("en_GB", "Englisch");
countries.add(german);
countries.add(english);
final ComboBox<Language> combo = new ComboBox<Language>();
combo.setWidth(100);
combo.setStore(countries);
combo.setDisplayField("langName");
combo.setTemplate(getFlagTemplate());
combo.setTypeAhead(true);
combo.setTriggerAction(TriggerAction.ALL);
combo.setValue(german);
This is the template for the ComboBox two show the selectable values.
private native String getFlagTemplate() /*-{
return [ '<tpl for=".">', '<div class="x-combo-list-item">',
'<img src="resources/images/lang/{langIcon}.png">',
' {langName}</div>', '</tpl>' ].join("");
}-*/;
How can i use an template for the displayField or is there an other possibility?
Thanks!
You need to implement a com.extjs.gxt.ui.client.widget.form.ListModelPropertyEditor.
The com.extjs.gxt.ui.client.widget.form.PropertyEditor#getStringValue returns the string that should be displayed and the com.extjs.gxt.ui.client.widget.form.PropertyEditor#convertStringValue converts the displayed string back into the model.
This isn't a very performant implementation but it works:
public class TemplateModelPropertyEditor<D extends ModelData> extends
ListModelPropertyEditor<D> {
/** Template to render the model. */
private XTemplate template;
#Override
public D convertStringValue(final String value) {
for (final D d : models) {
final String val = getStringValue(d);
if (value.equals(val)) {
return d;
}
}
return null;
}
#Override
public String getStringValue(final D value) {
if (template != null) {
final Element div = DOM.createDiv();
template.overwrite(div, Util.getJsObject(value));
return div.getInnerText();
}
final Object obj = value.get(displayProperty);
if (obj != null) {
return obj.toString();
}
return null;
}
public void setSimpleTemplate(final String html) {
template = XTemplate.create(html);
}
}
Usage:
TemplateModelPropertyEditor<Language> propertyEditor = new TemplateModelPropertyEditor<Language>();
propertyEditor.setSimpleTemplate(getFlagTemplate());
combo.setPropertyEditor(propertyEditor);
which imports?
I added these ones:
import com.extjs.gxt.ui.client.core.XTemplate;
import com.extjs.gxt.ui.client.util.Util;
import com.extjs.gxt.ui.client.widget.form.ListModelPropertyEditor;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
Everthing works fine, but it don't display an icon. When i debug the return div.getInnerText() method throws an error called: Method "getInnerText" with signature "()Ljava/lang/String;" is not applicable on this object.
The created div element looks okay
<DIV><DIV class=x-combo-list-item><IMG src="http://127.0.0.1:8888/resources/images/lang/de_DE.png"> Deutsch</DIV></DIV>