Java Reference
In-Depth Information
public class
UserDto {
private long
id;
private
String username;
private
String firstName;
private
String lastName;
// getters and setters omitted
}
Finally, because the persistence layer will be developed using
JPA
, a new implementa-
tion (
UserDaoJpaImpl
) is necessary, and its initial version is shown in listing 18.3.
3
Listing 18.3
Initial implementation of
UserDao
using JPA
public class
UserDaoJpaImpl
implements
UserDao {
private
EntityManager entityManager; // getters and setters omitted
public void
addUser(User user) {
entityManager.persist(user);
}
public
User getUserById(
long
id) {
return
entityManager.find(User.
class
, id);
}
public void
deleteUser(
long
id) {
String jql = "delete User where id = ?";
Query query = entityManager.createQuery(jql);
query.setParameter(1, id);
query.executeUpdate();
}
}
The sample application is available in two flavors, Maven and Ant. To run the tests on
Maven, type
'mvn
clean
test'
. Similarly, to use Ant instead, type
'ant
clean
test'
.
The application is also available as two Eclipse projects, one with the required libraries
(under the lib
directory)
and another with the project itself.
18.1.2
Multiple layers, multiple testing strategies
Because each application layer has different characteristics and dependencies, the lay-
ers require different testing strategies. If your application has been designed to use
interfaces and implementations, it's possible to test each layer in isolation, using
mocks or stubs to implement other layers' interfaces.
In our example, the business layer façade (listing 18.4) will be tested using Easy-
Mock as the implementation of the
DAO
interfaces, as shown in listing 18.5.
3
The astute reader might be wondering why we listed
UserDaoJpaImpl
in this chapter but omitted
UserDaoJdbcImpl
in chapter 17. The reason is that the JPA implementation is much simpler, just a few lines
of nonplumbing code.