Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

Tutorials
  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
Articles
Articles_pt
CreateDAO_es
SandBox




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateManager_es


This is version 3. It is not the current version, and thus it cannot be edited.
[Back to current version]   [Restore this version]


Parte II: Creating new Managers - Instrucciones para crear Fachadas de Logica de Negocios (Business Facades) que interaccionan con la capa de acceso a datos (DAO) y manejan todo lo relacionado con la gestion de transacciones.
Este tutorial depende de Part I: Creating new DAOs and Objects in AppFuse.

Sobre este tutorial

Este tutorial te mostrara como crear clases del tipo Business Facada (asi como test unitario ) para interactuar ,con la capa DAO creada in Part I.

En el contexto de AppFuse, crearemos lo que se llama una clase Manager. Su principal objetivo es la de servir de puente entre la capa de persistencia DAO y la capa de presentacion. Tambien permite aislar la capa de presentacion de la capa de persistencia(i.e. para aplicaciones Swing ). Ademas, contienen toda la logica de la aplicacion.

Te voy a decir como yo hago las cosas en la Vida Real en texto como este.

Vamos a empezar creando una clase ManagerTest y otra clase Manager en la arquitectura de AppFuse.

Tabla de Contenidos

  • [1] Crear una nueva clase ManagerTest para ejecutar tests JUnit con relacion a la clase Manager.
  • [2] Crear una nueva clase Manager que interaccionara con la capa DAO.
  • [3] Configurar Spring para la clase Manager y gestion de transacciones.
  • [4] Ejecutar la clase ManagerTest

Crear una nueva clase ManagerTest para ejecutar tests JUnit con relacion a la clase Manager. [#1]

En Part I,creamos una clase Person y PersonDao - por lo que vamos a seguir desarrollando esta entidad. Primero, crearemos una nueva clase de prueba JUnit para probar la clase PersonManager. Crea la clase PersonManagerTest en el directorio test/service/**/service. Vamos a probar los metodos basicos (leer, anadir, eliminar) que contiene nuestra clase.
El hecho de tener tantas clases de prueba puede parecer redundante, sin embargo, dentro de 6 meses nos seran de mucha ayuda.

This class should extend BaseManagerTestCase, which already exists in the service package. The parent class (BaseManagerTestCase) serves similar functionality as the BaseDaoTestCase.

I usually copy (open → save as) an existing test (i.e. UserManagerTest.java) and find/replace [Uu]ser with [Pp]erson, or whatever the name of my object is.

The code below is what you need for a basic JUnit test of your Manager. Unlike the DaoTest, this test uses jMock to isolate the Manager from its dependencies and make it a true "unit" test. This can be very helpful because it allows you to test your business logic w/o worrying about other dependencies. The code below simply sets up the Manger and its dependencies (as Mocks) for testing.


package org.appfuse.service;

import java.util.List;
import java.util.ArrayList;

import org.appfuse.dao.PersonDao;
import org.appfuse.model.Person;
import org.appfuse.service.impl.PersonManagerImpl;

import org.jmock.Mock;
import org.springframework.orm.ObjectRetrievalFailureException;

public class PersonManagerTest extends BaseManagerTestCase {
    private final String personId = "1";
    private PersonManager personManager = new PersonManagerImpl();
    private Mock personDao = null;
    private Person person = null;

    protected void setUp() throws Exception {
        super.setUp();
        personDao = new Mock(PersonDao.class);
        personManager.setPersonDao((PersonDaopersonDao.proxy());
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        personManager = null;
    }
}

Now that you have the skeleton done for this class, you need to add the meat: the test methods to make sure everything works. Here's a snippet from the DAO Tutorial tutorial to help you understand what we're about to do.

...we create methods that begin with "test" (all lower case). As long as these methods are public, have a void return type and take no arguments, they will be called by our <junit> task in our Ant build.xml file. Here's some simple tests for testing CRUD. An important thing to remember is that each method (also known as a test), should be autonomous.

Add the following methods to your PersonManagerTest.java file:


    public void testGetPerson() throws Exception {
        // set expected behavior on dao
        personDao.expects(once()).method("getPerson")
            .will(returnValue(new Person()));
        person = personManager.getPerson(personId);
        assertTrue(person != null);
        personDao.verify();
    }

    public void testSavePerson() throws Exception {
        // set expected behavior on dao
        personDao.expects(once()).method("savePerson")
            .with(same(person)).isVoid();

        personManager.savePerson(person);
        personDao.verify();
    }    

    public void testAddAndRemovePerson() throws Exception {
        person = new Person();

        // set required fields
        person.setFirstName("firstName");
        person.setLastName("lastName");

        // set expected behavior on dao
        personDao.expects(once()).method("savePerson")
            .with(same(person)).isVoid();
        personManager.savePerson(person);
        personDao.verify();

        // reset expectations
        personDao.reset();

        personDao.expects(once()).method("removePerson").with(eq(new Long(personId)));
        personManager.removePerson(personId);
        personDao.verify();

        // reset expectations
        personDao.reset();
        // remove
        Exception ex = new ObjectRetrievalFailureException(Person.class, person.getId());
        personDao.expects(once()).method("removePerson").isVoid();            
        personDao.expects(once()).method("getPerson").will(throwException(ex));
        personManager.removePerson(personId);
        try {
            personManager.getPerson(personId);
            fail("Person with identifier '" + personId + "' found in database");
        catch (ObjectRetrievalFailureException e) {
            assertNotNull(e.getMessage());
        }
        personDao.verify();
    }

This class won't compile at this point because we have not created our PersonManager interface.

I think it's funny how I've followed so many patterns to allow extendibility in AppFuse. In reality, on most projects I've been on - I learn so much in a year that I don't want to extend the architecture - I want to rewrite it. Hopefully by keeping AppFuse up to date with my perceived best practices, this won't happen as much. Each year will just be an upgrade to the latest AppFuse, rather than a re-write. ;-)

Create a new Manager to talk to the DAO [#2]

First off, create a PersonManager.java interface in the src/service/**/service directory and specify the basic CRUD methods for any implementation classes. I've eliminated the JavaDocs in the class below for display purposes. The setPersonDao() method is not used in most cases - its just exists so the PersonManagerTest can set the DAO on the interface.

As usual, I usually duplicate (open → save as) an existing file (i.e. UserManager.java).


package org.appfuse.service;

import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;

public interface PersonManager {
    public void setPersonDao(PersonDao dao);
    public Person getPerson(String id);
    public void savePerson(Person person);
    public void removePerson(String id);
}

Now let's create a PersonManagerImpl class that implements the methods in PersonManager. To do this, create a new class in src/service/**/service/impl and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager.


package org.appfuse.service.impl;

import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;
import org.appfuse.service.PersonManager;

public class PersonManagerImpl extends BaseManager implements PersonManager {
    private PersonDao dao;

    public void setPersonDao(PersonDao dao) {
        this.dao = dao;
    }

    public Person getPerson(String id) {
        return dao.getPerson(Long.valueOf(id));
    }

    public void savePerson(Person person) {
        dao.savePerson(person);
    }

    public void removePerson(String id) {
        dao.removePerson(Long.valueOf(id));
    }
}

One thing to note is the setPersonDao() method. This is used by Spring to bind the PersonDao to this Manager. This is configured in the applicationContext-service.xml file. We'll get to configuring that in Step 3[3]. You should be able to compile everything now using "ant compile-service".

Now you need to edit Spring's config file for our services layer so it will know about this new Manager.

Configure Spring for this Manager and Transactions [#3]

To notify Spring of this our PersonManager interface and its implementation, open the src/service/**/service/applicationContext-service.xml file. In here, you should see a commented out definition for the "personManager" bean. Uncomment this, or add the following to the bottom of this file.


    <bean id="personManager" parent="txProxyTemplate">
        <property name="target">
            <bean class="org.appfuse.service.impl.PersonManagerImpl" autowire="byName"/>
        </property>
    </bean>

The "parent" attribute refers to a bean definition for a TransactionProxyFactoryBean that has all the basic transaction attributes set.

Run the ManagerTest [#4]

Save all your edited files and try running ant test-service -Dtestcase=PersonManager.

Yeah Baby, Yeah: BUILD SUCCESSFUL
Total time: 9 seconds


The files that were modified and added to this point are available for download.

Next Up: Part III: Creating Actions and JSPs - A HowTo for creating Actions and JSPs in the AppFuse architecture.



Go to top   More info...   Attach file...
This particular version was published on 06-Nov-2006 13:52:48 MST by PatriaLukman.