Get ZK Up and Running with MVC"

From Documentation
(→‎Control Components: rename 2nd header)
Line 377: Line 377:
 
One of <tt>SelectorComposer</tt>'s features is allowing you to retrieve the UI component's object by annotating '''<tt>@Wire</tt>''' on controller's member variables.  
 
One of <tt>SelectorComposer</tt>'s features is allowing you to retrieve the UI component's object by annotating '''<tt>@Wire</tt>''' on controller's member variables.  
  
[[File:Icon-steps.png]]Steps:
+
 
 +
<div style="float:left;width:80px">
 +
[[File:Icon-steps.png]]
 +
</div>
 +
Steps:
 
# Declare a variable with corresponding component type (e.g. <tt>Listbox</tt>, <tt> Label</tt>...)
 
# Declare a variable with corresponding component type (e.g. <tt>Listbox</tt>, <tt> Label</tt>...)
 
# Variable's name is the same as component's id. <ref> In fact, matching id is the default rule to match a component for <tt>@Wire</tt>, and please refer to [[ZK Developer's Reference/MVC/Controller/Wire Components| Wire Components]] to know other ways</ref>
 
# Variable's name is the same as component's id. <ref> In fact, matching id is the default rule to match a component for <tt>@Wire</tt>, and please refer to [[ZK Developer's Reference/MVC/Controller/Wire Components| Wire Components]] to know other ways</ref>
 
# Annotate the variable with <tt>@Wire</tt>.
 
# Annotate the variable with <tt>@Wire</tt>.
 +
 +
  
 
Then <tt>SelectorComposer</tt> will "wire" a corresponding ZK component object to the variable you declared. After this has been done, you can then control and manipulate UI by accessing those annotated member variables.
 
Then <tt>SelectorComposer</tt> will "wire" a corresponding ZK component object to the variable you declared. After this has been done, you can then control and manipulate UI by accessing those annotated member variables.

Revision as of 07:25, 19 July 2012

WarningTriangle-32x32.png This page is under construction, so we cannot guarantee the accuracy of the content!

Introduction

This tutorial is intended for software developers who have experience in writing Java program with Eclipse. We will guide you how to build a modern web application with ZK. The target application we are going to build is a simple bookstore catalog application. You will also learn basic concepts of ZK during this tutorial.

You can take look at [http:// target application's live demo].

We also provide the complete source code with an Eclipse project zip file in Download section. To run the application please refer to Run on Server


Warm Up

Prerequisite

We use Eclipse IDE 3.7 (indigo) for Java EE developer Eclipse-javaee.png (Download Eclipse) to demonstrate the whole instructions.


Download ZK

Download the ZK CE (file name should be zk-bin-6.0.2.zip) and extract it to a folder.


Create a Web Project

Open Eclipse.

  1. select File \ New \ Dynamic Web Project
  2. enter zktutorial in Project name and keep every thing else default.

Tutorial-newproject.png


Add ZK JAR to Your Project

To use ZK in your project, you have to copy ZK JAR into your project's library folder.

Copy JAR files under following list to zktutorial/WEB-INF/lib:

  • {YOUR_ZK_UNZIP_FOLDER}/dist/lib
  • {YOUR_ZK_UNZIP_FOLDER}/dist/lib/ext


Create a Simple Page

After installation, you can create a simple zul to verify the installation works or not. In Eclipse,

  1. select File / New / File or File / New / Other / File to add a new file, hello.zul, under WebContent.
  2. Copy and paste the following sample code into hello.zul and save it.


hello.zul

 <window title="My First ZK Application" border="normal">
 	Hello World!
 </window>



After complete previous 2 steps, your project may look like:

Tutorial-project-structure.png

Setup XML Editor

Because Eclipse doesn't recognize the file extension name "zul" by default, we should add "zul" as a content type of XML format.

  1. Select Window \ Preferences to enter Preferences window
  2. In left tree, select General / Content Types, on right hand side, expand Text node in "Content types" box, select XML
  3. Click Add button, type *.zul, and click OK button


Tutorial-add-contenttype.png


After this setup, when you double click a zul file, Eclipse will use XML editor to open it with syntax hightlight.

Tutorial-xmleditor.png


Create New Server

Before running a web application, we must create a server in Eclipse. In Servers view, click new server wizard... (or right click and select New \ Server)

Tutorial-addserver.png


Select Manually define a new server and select Tomcat v7.0 Server . Then click "Next".

Tutorial-newserver.png


If you have installed Tomcat 7 before, just provide your path. If you don't, proceed the following step:

  1. click Download and Install button and choose a folder
  2. accept the license agreement, wait for a minute.
    Eclipse will download and install Tomcat into the folder you specified. After installation is complete, the Finish button will become enabled.
  3. Click Finish button to complete it.

Tutorial-downloadinstall.png


Run the Application

Right click on hello.zul, in context menu, select Run As / Run on Server to run this zul on an application server.

Tutorial-runonserver.png


Choose an existing Tomcat 7. Yon can also check Always use this server when running this project option to avoid choose a server again in the future.

Tutorial-choose-server.png


Eclipse opens an internal browser automatically and connects to http://localhost:8080/hello.zul. If you can see the following image, then your installation is success.

Tutorial-hello.png


Our setup steps are designed for those application servers that support Servlet 3.0. If you prefer to use older Servlet specification, please refer to ZK Installation Guide. [1]

Example Application

Our target application is a simple bookstore catalog application. This application only has 2 main functions:

  1. Search books.
    Enter a keyword in the textbox on the upper part of a window, click search button and it displays the search result in the book list below.
  2. View details.
    Click any item of the book list, then the area below the book list shows the selected book's detail data including name, price, description, and cover preview.


Tutorial-searchexample.png


The following is the domain object that represents a book.

public class Book {
	private Integer id;
	private String name;
	private String thumbnail;
	private String description;
	private Float price;
	//omit getter and setter for brevity
}
  • Please refer to References section to see the complete code. [2]


Then we define a service class to perform the business logic (search books) as follows:

public interface BookService {

	/**
	 * Retrieve all books in the bookstore.
	 * @return all books
	 */
	public List<Book> findAll();
	
	/**
	 * search books according to keyword.
	 * @param keyword book name's keyword
	 * @return list of book that match the keyword
	 */
	public List<Book> search(String keyword);
}

We have a BookServeImpl that implements above interface. For simplicity it uses a static list object as the data model. You can replace it with connecting to a database in a real application. The implementation detail is not in this article's scope, please refer to References section.[3]

Sketch User Interface

Photo pencil.jpg

Design UI is a good step to start building an application, since it helps you define the scope of your application. ZK provides hundreds of ready-made UI components. Developers can rapidly build their desired own user interface by combining these components without creating from scratch.

In ZK, you can use ZK User Interface Markup Language (ZUML) [4], an XML-formatted language, to describe user interface. In ZK default convention, the files to describe user interface use .zul as file name suffix. One XML element (tag) represents a component, and each component's style, behavior, and function can be configured by setting XML element's attributes.[5] For example, the following code is a window with specified title and normal border of our example application.


Extracted from search.zul

	<window title="Search Product" width="800px" border="normal">
		<!-- put child components inside a tag's body -->
	</window>

We use a window as our application's frame. As it is the outmost component, it's called the root component. Window is a mostly common used container because it's a basic display element of a desktop-like application and it can also encloses other components. All other components inside the window should be put in window tag's body, and they are called child component. We set window's title bar text with "title" attribute and make window display a normal border with "border" attribute. For "width" attribute, use CSS like syntax such as "800px", "60%". The "style" attribute allows you to customize component's style with CSS syntax.


Basically, our example application's user interface is divided into 3 areas inside a window, they are (from top to bottom) search function, book list, and book details area.

search

book list

book details


Search Area. ZK components are like building blocks, you can combine existing components to construct your desired user interface. To allow users to search, we need a place to enter keywords, a button for triggering search, and a text to tell user what they should input. We can use following zk components to fulfill this requirement:

Extracted from search.zul

	 	<hbox align="center">
	 		<label>Book Name Keyword:</label>
	 		<textbox id="keywordBox" />
	 		<button id="searchButton" label="Search" image="/img/search.png" />
	 	</hbox>

The hbox ("h" means horizontal) is a layout component and it can arrange its child components in horizontal order. Because these three child components have different height, we use "align" attribute to arrange them for elegance. Here we specify "id' attribute for some components in order to control them, and we'll talk about the reason in next section. You can easily create an image button by specifying path at "image" attribute.


Book List Area. ZK provides several components to display a collections of data such as listbox, grid, and tree. We use listbox to display a list of book with 2 columns: Name and Price. The "rows" attribute is used to control how many rows are visible and you can drag scroll-bar to see the rest of rows. The listbox is a container component, and you can add listhead to define a column. The listitem is used to display data, and the number of listcell corresponds to the number of listheader.

Extracted from search.zul

	 	<listbox id="productListbox" rows="5">
			<listhead>
				<listheader label="Name" />
				<listheader label="Price" />
			</listhead>
			<listitem>
				<listcell value="product name"></listcell>
				<listcell>$<label value="price" /></listcell>
			</listitem>
		</listbox>



Book Details Area. Like the hbox, vbox is a layout component which arranges its child component in vertical order. By combing these 2 layout components, we can present more information on a screen.

Extracted from search.zul

		<hbox style="margin-top:20px">
			<image id="thumbImage" width="250px" />
			<vbox>
				<label id="nameLabel" />
				<label id="priceLabel" />
				<label id="descriptionLabel"/>
			</vbox>
		</hbox>


You can see complete zul through the link in reference section. [6]

Control Components

Tutorial-control.jpg

The next step after sketching the UI is to make UI response to users. In ZK, we have 2 approaches to design an application, the first approach we introduce here is to control ZK UI component (Java object) directly by yourself in a controller. This approach can be classified to Model-View-Controller (MVC) design pattern. [7] This approach divides an application into three parts.

The Model consists of application data and business rules.BookService and other classes used by it represent this part in our example application.

The View means user interface. The zul page which contains ZK components represents this part. An user's interaction with components triggers events to be sent to controllers.

The Controller plays as a coordinator between View and Model. It receives events from View to update Model and retrieve data to change View's presentation. ZK composer represents this part.


Zktutorial-mvc-interaction.png

  1. When a user interacts with a component (e.g. click a button) on a ZUL, the user's action triggers an event.
    This event is sent to ZK composer (controller) and invoke users-implemented event listener method.
  2. The event listener that is corresponding to the component is invoked.
  3. The event listener method usually executes business logic or accesses data, then manipulate ZK components.
  4. Component's change made in event listeners reflects to UI change.


Tutorial-target.pngIn this chapter, you'll learn:

  1. How to handle a component's event
  2. How to control components in a composer
  3. How to use template

UI Controller

In ZK, the controller is responsible for controlling ZK components and listening events which are triggered by user interaction.

In order to control UI in ZK, you have to implement a controller class for a ZUL. You can simply extends SelectorComposer :

package tutorial;

// omit import for brevity

public class SearchProductController extends SelectorComposer<Component> {

}


After a composer is implemented, you should associate it to a component in a zul file, so that the composer can control the component including its child components. Associating a composer to a component is just specifying full-qualified class name in target component's apply attribute. The following code shows how to associate a composer to a window.

	<window title="Search Product" width="800px" border="normal"
	apply="tutorial.SearchProductController">
	<!-- omit other components for brevity -->
	</window>



When we associate a composer to a component, every event triggered by this component (and its child components) is sent to the composer. If there is a event listener method that corresponds to the component's event, it will be invoked. When a user interact with a component, ZK sends events automatically upon user's actions. For example, click a button issues an "onClick" event, select an item in a listbox issues an "onSelect" event. You don't need to worry about events generating.

Let's start from search function: an user enters a keyword, click the "Search" button to trigger the search. So, we should write codes to response clicking "Search" button.

Icon-steps.png Steps to handle an user's action:

  1. Declare a public method and specify which component's event this method listens
    Make the method listen "Search" button's "onClick" event.
  2. Control UI components to implement presentation logic
    Get the keyword value and pass to BookService to search for result.


1. Handle User Action


We declare a method, search() , to be invoked when "Search" button is clicked, so we can specify the relationship with syntax:

@Listen("[EVENT_NAME] = #[COMPONENT_ID]").

The final code looks like:

public class SearchProductController extends SelectorComposer<Component> {

	@Listen("onClick = #searchButton")
	public void search(){

	}
}
  • Line 3: There are other syntax to specify @Listen's parameter. [8]
  • Line 4: It must be a public method.

2. Control ZK Component

One of SelectorComposer's features is allowing you to retrieve the UI component's object by annotating @Wire on controller's member variables.


Icon-steps.png

Steps:

  1. Declare a variable with corresponding component type (e.g. Listbox, Label...)
  2. Variable's name is the same as component's id. [9]
  3. Annotate the variable with @Wire.


Then SelectorComposer will "wire" a corresponding ZK component object to the variable you declared. After this has been done, you can then control and manipulate UI by accessing those annotated member variables.

public class SearchProductController extends SelectorComposer<Component> {

	@Wire
	private Listbox productListbox;

	//other codes...
}
  • In mentioned search.zul, there is a listbox whose id is "productListbox". SelectorComposer will make productListbox reference to the listbox object after components are created.


The search method performs simple logic: call book service class to search with keyword and set result list to listbox. For a variable which references to a component, we can get data from zul such as user's input, or a button's visibility with getter (e.g. getValue()) or change it status like making a label red with setter to achieve some dynamic UI effect. Hence, we can easily get what keyword a users input by keywordBox.getValue() and change data item of listbox by productListbox.setModel() .

public class SearchProductController extends SelectorComposer<Component> {
	//omit codes to get components

	@Listen("onClick = #searchButton")
	public void search(){
		String keyword = keywordBox.getValue();
		List<Book> result = bookService.search(keyword);
		productListbox.setModel(new ListModelList<Book>(result));
	}
}
  • Line 8: Notice that setModel() only accepts ListModel object, because listbox needs to control selection. We can use ListModelList to wrap search result list. There are other ListModel object for different collection types, please refer to reference section. [10]

Display a Collection of Data

We have successfully made "Search" button invoke event listener, but you still find that content of listbox doesn't show search result. That is because we don't specify how to render data model of listbox. Now, we will use a special tag, <template> to control the rendering of each item. ZK will render template tag's content repeatedly for each object in model of listbox.

Icon-steps.pngSteps:

  1. Use <template> to enclose components that you want to render repeatedly.
  2. Set template's name attribute to "model".
  3. Use implicit variable each to assign domain object's properties to component's attributes.
    The "each" is a variable that references to a domain object in the model list, you can use it to access domain object's property with EL, e.g. ${each.name}


	 	<listbox id="productListbox" rows="5">
			<listhead>
				<listheader label="Name" />
				<listheader label="Price" />
			</listhead>
			<template name="model">
				<listitem>
					<listcell label="${each.name}"></listcell>
					<listcell>$<label value="${each.price}" /></listcell>
				</listitem>
			</template>
		</listbox>
  • Line 5: The template tag's "name" attribute should be model and be declared inside the listbox.
  • Line 8: The implicit variable ${each}" represents an object of the model which is Book in our example application.


Implement View Details Function

The steps to implement view details function is similar to search. We use @Wire to get components including thumbImage, nameLabel, priceLabel, and descriptionLabel and stuff data to them with setter in a method. Then declare that method to listen "onSelect" event of listbox with @Listen.

public class SearchProductController extends SelectorComposer<Component> {

	@Wire
	private Listbox productListbox;
	@Wire
	private Label nameLabel;
	@Wire
	private Label priceLabel;
	@Wire
	private Label descriptionLabel;
	@Wire
	private Image thumbImage;

	@Listen("onSelect = #productListbox")
	public void showDetail(){
		Book selectedBook = productListbox.getSelectedItem().getValue();
		thumbImage.setSrc(selectedBook.getThumbnail());
		nameLabel.setValue(selectedBook.getName());
		priceLabel.setValue("$"+selectedBook.getPrice());
		descriptionLabel.setValue(selectedBook.getDescription());
		
	}
}


For complete source code, please refer to Reference section [11]

Data Binding

The second approach to handle user interaction is to let ZK control UI component for you. This approach is classified to Model-View-ViewModel (MVVM) design pattern. [12] This approach also divides an application into three parts. Only ViewModel is the different part from MVC. The ViewModel acts like a special Controller for the View which is responsible for exposing data from the Model to the View and for providing required action and logic for user requests from the View. The ViewModel is type of View abstraction, which contains a View's state and behavior. But ViewModel should contain no reference to UI components and knows nothing about View's visual elements.

Under this approach, you just prepare a ViewModel class with proper setter, getter and data binding annotation. Then specify data binding expression on component's attributes. ZK's data binding mechanism will load and save data from ViewModel and handle events automatically according to your binding expression in a zul. You don't need to control components by yourself.


Here we use search scenario to explain how MVVM works in ZK. Assume that a user click "Search" button then listbox updates its content. The flow is as follows:

Tutorial-mvvm.png


  1. A user clicks "Search" button.
  2. A corresponding event is fired.
  3. The data binding mechanism finds the corresponding method (Command) in the ViewModel and invokes it.
  4. The method accesses data from Model layer and updates some ViewModel's properties.
  5. ViewModel notify data binding mechanism that some properties have been changed.
  6. Per what properties have been changed, data binding mechanism loads data from the ViewModel.
  7. Data binding mechanism then updates the corresponding UI components to provide visual feedback to the user.


Tutorial-target.pngIn this chapter, you'll learn:

  1. How to implement a ViewModel
  2. How to use data binding
  3. How to use command binding and change notification

ViewModel

In ZK, ViewModel can be simply a POJO, and it should not contain any variable which references to UI components.

Icon-steps.pngSteps to associate a ViewModel to a zul:

  1. Implement a ViewModel class
  2. Set target component's apply and viewModel attribute


Creating a ViewModel is like creating a POJO, and it exposes its properties like JavaBean through setter and getter methods.

package tutorial;

//omit import statements

public class SearchViewModel{
	//declare properties, setter, and getter methods

	private String keyword;

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
}


We can bind ZK UI component to a ViewModel by setting a component's viewModel attribute, and that component becomes the Root View Component for the ViewModel. All child components of this Root View Component can acces the same ViewModel and its properties. To bind a ViewModel, we have to apply a composer called org.zkoss.bind.BindComposer, it will create a binder for the ViewModel and instantiate the ViewModel's class. Then we use ZK Bind annotations to set ViewModel's id in @id and the ViewModel's full-qualified class name in @init . The id is used to reference ViewModel's properties, e.g. vm.name, whilst the full-qualified class name is used to instantiate the ViewModel object itself.

	<window title="Search Product" width="800px" border="normal" 
		apply="org.zkoss.bind.BindComposer" viewModel="@id('vm')@init('tutorial.SearchViewModel')">
	<!-- omit other tags-->
	</window>



When we associate a ViewModel to a component, we can bind attributes of this component (and its child components) to the ViewModel. When a user interact with components, ZK sends events automatically to the ViewModel like the case in MVC. ViewModel has its own way to specify event handlers.

Let's also start from search function: an user enters a keyword, click the "Search" button to trigger the search. So, we should write codes to response clicking "Search" button.

1. Bind Properties to Component Attributes

The ViewModel class should contain data for components. You should provide getter method for loading data to a component and setter method for saving component's data back to Viewmodel. In our example, we declare keyword for text and bookList for listbox.

public class SearchViewModel {

	private String keyword;
	private List<Book> bookList;

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	
	public List<Book> getBookList(){
		return bookList;
	}
}

Then we can bind "value" of textbox to vm.keyword with @save(vm.keyword), because we want to save user input value into ViewModel. Remember that vm is the id we used to reference ViewModel and we give it in @id() in previous section. We use @load to load book list from ViewModel.

		<hbox>
			<label>Book Name Keyword:</label>
			<textbox value="@save(vm.keyword)" />
			<button label="Search" image="/img/search.png" />
		</hbox>
		<listbox id="productListbox" rows="5" model="@load(vm.bookList)" >
		<!-- omit other tags -->

2. User Actions as Commands

In ZK MVVM, we treat every event as a command to the ViewModel, and we write a Command method with @Command to handle this event. Thus, when a user action triggers an event, the ViewModel's corresponding command method is executed. The method may update properties value or perform business logic with service class.

Icon-steps.png The steps to bind an event to ViewModel's command method:

  1. Specify an event attribute with @command('commandName')
  2. Implement a method which has name as command name and annotate with @Command
  3. Notify properties change with @NotifyChange


In order to handle clicking on "Search" button, we specify button's onClick attribute. It's better to give a meaningful command name upon your context.

		<hbox>
			<label>Book Name Keyword:</label>
			<textbox value="@save(vm.keyword)" />
			<button label="Search" image="/img/search.png" onClick="@command('search')" />
		</hbox>


Then we implement a method to search with keyword and annotate it with @Command to complete the binding relationship. When a user clicks the "Search" button, ZK will invoke search().

public class SearchViewModel {
	
	@Command
	public void search(){
		bookList = bookService.search(keyword);
	}
}


Now, we have handled button clicking but search result still doesn't update. Why? Why doesn't ZK load data from ViewModel? Because it doesn't know when or which data to reload. In MVVM approach, we can't stuff data into components directly. We have to notify ZK to load the data for us. After search() is invoked, we store search result in bookList. Hence, we should notify ZK to reload the property "bookList" as follows:

public class SearchViewModel {

	@NotifyChange("bookList")
	@Command
	public void search(){
		bookList = bookService.search(keyword);
	}
  • Line 3: If you want to notify multiple properties, use array format: @NotifyChange({"property01","property02"})


View Details Function

The steps to implement view details function are similar to search.

  • We first declare a variable selectedBook to store selected item of listbox in the ViewModel and bind attribute selectedItem of listbox to the variable with @save(vm.selectedBook).
  • Because we want to show selected book's, we bind labels value and images src to selected book's properties which can be access by dot notation like vm.selectedBook.name.
  • Each time when a user selects a listitem, ZK will set the data object to variable selectedBook. Then ZK will reload selectedBook's properties to those bound attributes.

You may think why does ZK know to reload selectedBook's properties when they are changed? Because setter method has default notification by default', ZK will reload the target property changed by setter method automatically. You don't need to specify @NotifyChange to notify ZK the changed property itself.


		<listbox rows="5"
		  model="@load(vm.bookList)" selectedItem="@save(vm.selectedBook)">
		<!-- omit child components -->
		</listbox>
		<hbox style="margin-top:20px">
			<image width="250px" src="@load(vm.selectedBook.thumbnail)" />
			<vbox>
				<label value="@load(vm.selectedBook.name)" />
				<label value="@load(vm.selectedBook.price)" />
				<label value="@load(vm.selectedBook.description)" />
			</vbox>
		</hbox>

Patterns Comparison

MVC v.s MVVM

When to use

Restriction

Unit Test ZK Application

ZK provides a unit test library, Mimic, which is one module of ZK Application Test Suite (ZATS). ZATS Mimic enables you to test your composer without an application server and of course without a browser either. Through this library, testers can mimic user interactions to applications such as clicking or typing to verify composer's or ViewModel's (controller layer) data and logic. All you have to do is to write a regular unit test case and use Mimic's utility class to interact components on ZUL and then, run the test case.

No deploying to server, no rendering on browser, the unit test case can be executed in a very short period of time - this is very helpful for frequent unit testing during a agile development process.

We are going to demonstrate how to test our example application with ZATS Mimic.

Setup

  • Download ZATS Mimic Binary
    Add all jar files under dist/lib and dist/lib/ext into your project's classpath. Note that please do not deploy these jars to your application server, they are for testing only.
  • Add JUnit library to your project.
    Right click the zktutorial project, Select Properties to enter project properties window. Select Java Build Path, click add Library, select JUnit, select JUnit 4 in dropdown listbox, then click "Finish" button.


Tutorial-add-junit.png


Write a Test Case

Icon-steps.pngSteps to write a test case are as follows:

  1. Setup web application content path
  2. Create a client to connect to a ZUL
  3. Query a component
  4. Perform an operation on a component
  5. Verify result by checking a component’s property
  6. Tear down, stop server emulator


Fundamental Classes

Before showing source code, there are some basic classes you should know first.

Zats
It contains several utility methods to initialize and clean testing environment. By default, it starts server emulator with built-in web.xml and zk.xml bundled in ZATS Mimic's jar.
DesktopAgent
Wraps ZK Desktop object, we usually call its query() or queryAll() to retrieve ComponentAgent with selector syntax.
For available selector syntax, please refer to SelectorComposer or Small Talks/2011/January/Envisage ZK 6: An Annotation Based Composer For MVC
ComponentAgent
Mimics a ZK component and determines which operation you can perform on it. We can also get ZK component property's value from it.
It also has query() which means to find targets among its child components.
OperationAgent (ClickAgent, TypeAgent, SelectAgent...)
To mimic a user operation to a ZK component.
We name it "Agent" as it's not really the user operation itself, it's an agent to mimic user operation to a component.


Test Case Example

The steps we implement in test case to verify our example application are:

  1. mimic entering "java" in the textbox
  2. clicking "Search" button
  3. select each listitems in result list
  4. verify book's name in details area contains the keyword.
public class TestSearch {

	@BeforeClass
	public static void init() {
		Zats.init("./src/main/webapp"); // set web application root folder
	}

	@Test
	public void test() {
		DesktopAgent desktop = Zats.newClient().connect("/search.zul");

		//enter keyword and click button
		String keyword = "java";
		ComponentAgent keywordBox = desktop.query("#keywordBox");
		keywordBox.as(InputAgent.class).type(keyword);
		desktop.query("#searchButton").as(ClickAgent.class).click();
		
		//find all listitems
		List<ComponentAgent> searchResult = desktop.queryAll("listitem");
		for (ComponentAgent listitem : searchResult){
			//select a listitem
			listitem.as(SelectAgent.class).select();
			String bookName = desktop.query("#nameLabel").as(Label.class).getValue();
			Assert.assertTrue(bookName.toLowerCase().contains(keyword));
		}
	}

	@AfterClass
	public static void end() {
		Zats.end();
	}

	@After
	public void after() {
		Zats.cleanup();
	}
}
  • Line 10: Create a client to visit our target zul.
  • Line 14: Query in desktop to retrieve the textbox for keyword with its component's id.
  • Line 15: You should convert ComponentAgent to InputAgent in order to type in a textbox.
  • Line 16: Get the button and click it in one statement.
  • Line 19: The queryAll() retrieves all components that match selector syntax as a list.
  • Line 22: To select a listitem", you have to get it first and convert it to SelectAgent.
  • Line 23: You can also convert ComponentAgent to its native component type e.g. Label in order to get component's status.
  • Line 24: We verify component's status with JUnit's assert methods.

Download

[Example application zip file]

Reference

  1. Create and Run Your First ZK Application Manually
  2. [http:// Book.java]
  3. [http:// BookService.java] [http:// BookServiceImpl.java]
  4. ZUML Reference
  5. ZK Component Reference
  6. [http:// source code of search.zul]
  7. MVC in Developer's Reference
  8. selector syntax
  9. In fact, matching id is the default rule to match a component for @Wire, and please refer to Wire Components to know other ways
  10. List Model in Developer's Reference
  11. [http:// SearchProductController.java]
  12. MVVM in Developer's Reference