Java Reference
In-Depth Information
as DOM objects. In listing 14.10, we use the provided HTML DOM to verify that the
returned web page contains the expected HTML table.
In this section we described how to test the frontend of the Administrator applica-
tion. What we're still missing is a few pages that will reveal to us how to unit test the
AdministratorBean EJB , which executes our queries on the database. The secrets of
EJB testing are covered in the next section.
14.5
Testing EJBs
Te s t i n g EJB s has a reputation of being a difficult task. One of the main reasons is that
EJB s are components that run inside a container. You need to either abstract out the
container services used by your code or perform in-container unit testing. In this sec-
tion, we demonstrate different techniques that can help you write EJB unit tests. We
also continue developing our Administrator application, showing you the module that
executes the SQL queries.
The architecture of the Administrator application goes like this: The command to
be executed gets through the filter, which determines whether it's a SELECT query.
After that, the AdminServlet eventually receives the command/query.
The execution flow starts in the AdminServlet doGet method. It receives the HTTP
requests and calls the getCommand method to extract the SQL query from it. It then
calls executeCommand to execute the database call (using the extracted SQL query)
and return the results as a Collection . The results are then put in the HTTP request
(as a request attribute) and, at last, doGet calls callView to invoke the JSP page that
presents the results to the user. So far, we've given no implementation of the execute-
Command method. The idea behind it would be to call a given EJB , which would execute
the query on a given database. One simple implementation of the executeCommand
method would be as follows:
public Collection executeCommand(String command) throws Exception {
Context context = new InitialContext();
IAdministratorLocal administrator = (IAdministratorLocal)
context.lookup(“AdministratorBean”);
return administrator.execute(command);
}
The EJB itself is shown in listing 14.11.
Listing 14.11 AdministratorEJB
[...]
@Stateless
public class AdministratorBean implements IAdministratorLocal {
public Collection execute(String sql) throws Exception {
Connection connection = getConnection();
// For simplicity, we'll assume the SQL is a SELECT query
ResultSet resultSet =
connection.createStatement().executeQuery(sql);
RowSetDynaClass rsdc = new RowSetDynaClass(resultSet);
B
C
 
 
 
 
 
Search WWH ::




Custom Search