Skip to main content

JUnit con DataClassG

JUnit con DataClassG
0. ESQUEMA




Services:

Por cada beans crearemos una clase Services que se encargarĆ” de interactuar con el controller para realizar las operaciones de la base de datos.
Se crearan los mƩtodos insert, update,delete y los demas metodos para realizar las diversas operaciones.

Test:
Se crearƔn las clases para test de las clases Services.

Form:
Los formularios para la interactuar con el usuario.
ProvinciasServices.java colocamos los mƩtodos, insert, update,delete

public class ProvinciasServices {
   ProvinciasController provinciasController = new ProvinciasController();

   public ProvinciasServices() {
   }
   public Boolean insert(Provincias provincias){
       try{
           if(provinciasController.insert(provincias)){
             return true;
           }else{
               Mensajeria.MensajeWarning(provinciasController.getMensaje(), "insert()");
           }
        } catch (Exception ex) {
           Mensajeria.MensajeError(ex,"insert()");
       }
       return false;
   }
   
   public Boolean update(Provincias provincias){
       try{
           if(provinciasController.update(provincias)){
             return true;
           }else{
               Mensajeria.MensajeWarning(provinciasController.getMensaje(), "update()");
           }
        } catch (Exception ex) {
           Mensajeria.MensajeError(ex,"update()");
       }
       return false;
   }
   


   public Boolean delete(Provincias provincias){
       try{
           if(provinciasController.delete(provincias)){
             return true;
           }else{
               Mensajeria.MensajeWarning(provinciasController.getMensaje(), "delete()");
           }
        } catch (Exception ex) {
           Mensajeria.MensajeError(ex,"delete()");
       }
       return false;
   }
}

Ahora creamos el test a partir de la clase existente.
Antes de crear la clase en el paquete pruebas seleccionar JUnit Test, y en categorĆ­as Test for 
Existing Class



Seleccionamos la clase
Clase de test generada

Se generan los mƩtodos con la palabra test al inicio

public class ProvinciasServicesTest extends TestCase {
      public ProvinciasServicesTest(String testName) {
       super(testName);
   }
   
   @Override
   protected void setUp() throws Exception {
       super.setUp();
   }
   
   @Override
   protected void tearDown() throws Exception {
       super.tearDown();
   }
   /**
    * Test of insert method, of class ProvinciasServices.
    */
   public void testInsert() {
       System.out.println("insert");
       Provincias provincias = null;
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = null;
       Boolean result = instance.insert(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
       fail("The test case is a prototype.");
   }

   /**
    * Test of update method, of class ProvinciasServices.
    */
   public void testUpdate() {
       System.out.println("update");
       Provincias provincias = null;
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = null;
       Boolean result = instance.update(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
       fail("The test case is a prototype.");
   }
   /**
    * Test of delete method, of class ProvinciasServices.
    */
   public void testDelete() {
       System.out.println("delete");
       Provincias provincias = null;
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = null;
       Boolean result = instance.delete(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
       fail("The test case is a prototype.");
   }
}

Agregar debajo de la definiciĆ³n de la clase
   DataGManager dataGManager = new DataGManager();
       Connection OpenConnection = dataGManager.OpenConnection();
Esto es para utilizar DataGManager




Ahora comentados todos las instrucciones fail de todos los mƩtodos
comentados

En el  mĆ©todo testInsert()
En la lĆ­nea   Boolean expResult = null; indica el valor de retorno del mĆ©todo
esperamos que el mĆ©todo insert() devuelva true.asĆ­i que colocamos el valor que esperamos que retorne el mĆ©todo si la operaciĆ³n fue exitosa
Boolean expResult = true;

public void testInsert() {
       System.out.println("insert");
       Provincias provincias = null;
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = null;
       Boolean result = instance.insert(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
      // fail("The test case is a prototype.");
  }

Localizamos el objeto provincias
Provincias provincias = null;
usamos el operador new al objeto provincias
Provincias provincias = new Provincias();

y le asignamos valores al objeto que serƔ pasado al mƩtodo insert
provincias.setProvincia("Los Santos");
        provincias.setIdprovincia("7");

QuedarĆ­a de la siguiente manera
 public void testInsert() {
       System.out.println("insert");
       Provincias provincias = new Provincias();
        provincias.setProvincia("Los Santos");
        provincias.setIdprovincia("7");
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = true;
       Boolean result = instance.insert(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
      // fail("The test case is a prototype.");
   }

Ajustamos los mƩtodos update y delete.


Clase terminada

public class ProvinciasServicesTest extends TestCase {
   
   public ProvinciasServicesTest(String testName) {
       super(testName);
   }
   
   @Override
   protected void setUp() throws Exception {
       super.setUp();
   }
   
   @Override
   protected void tearDown() throws Exception {
       super.tearDown();
   }

   /**
    * Test of insert method, of class ProvinciasServices.
    */
   public void testInsert() {
       System.out.println("insert");
       Provincias provincias = new Provincias();
        provincias.setProvincia("Los Santos");
        provincias.setIdprovincia("7");
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = true;
       Boolean result = instance.insert(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
      // fail("The test case is a prototype.");
   }

   /**
    * Test of update method, of class ProvinciasServices.
    */
   public void testUpdate() {
       System.out.println("update");
       Provincias provincias = new Provincias();
      provincias.setProvincia("Los Santos.");
        provincias.setIdprovincia("7");
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult =true;
       Boolean result = instance.update(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
      // fail("The test case is a prototype.");
   }

   /**
    * Test of delete method, of class ProvinciasServices.
    */
   public void testDelete() {
       System.out.println("delete");
       Provincias provincias = new Provincias();
        provincias.setIdprovincia("7");
       ProvinciasServices instance = new ProvinciasServices();
       Boolean expResult = true;
       Boolean result = instance.delete(provincias);
       assertEquals(expResult, result);
       // TODO review the generated test code and remove the default call to fail.
     //  fail("The test case is a prototype.");
   }
}


Ejecutamos el test




Podemos ver el resultado del test


No pasĆ³ el testInsert(), Indica que no se insertĆ³, ya que habĆ­a un registro con ese idprovincia en la tabla,testDelete no lo paso ya que el registro estaba relacionado u otra situaciĆ³n indicandonos que debemos revisar esos mĆ©todos.


Otra prueba del test, funciono el metodo testInsert, indicando que se inserto el registro, pero no lo puedo eliminar ni actualizar.

Si se ejecutan las pruebas nuevamente

si el test falla se enviaran mensajes de dialogo como este, esto puede ser un inconveniente si deseamos usar un sistema de integraciĆ³n continua.  MĆ”s adelante mostraremos la otra forma de hacerlo.


La ventaja de usar el Warning en el controller es que el invocar el services no tendrƭamos que generar estas advertencias en el mƩtodo que realiza el llamado.
En la clase donde se invoca sĆ³lo usarĆ­amos el siguiente cĆ³digo.


Comments

Anonymous said…
just dropping by to say hi
Anonymous said…
Informative article, just what I wanted to find.


Also visit my web blog genghis khan quotes
Anonymous said…
Today, I went to the beachfront with my kids.

I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the
shell to her ear and screamed. There was a hermit crab inside and it pinched her ear.
She never wants to go back! LoL I know this is totally off topic but
I had to tell someone!

My blog tired quotes
Anonymous said…
Hey! I know this is kind of off-topic but I had to ask.
Does running a well-established website like yours take
a large amount of work? I am brand new to operating a blog however I do write in my journal every day.
I'd like to start a blog so I can share my own experience and thoughts online. Please let me know if you have any ideas or tips for brand new aspiring blog owners. Appreciate it!

Look into my web blog: future quotes
Anonymous said…
Hi! I could have sworn I've visited this web site before but after going through some of the articles I realized it's new to me.
Anyways, I'm certainly pleased I stumbled upon it and I'll be bookmarking it and checking back regularly!


Feel free to visit my web site; friedrich nietzsche quotes
Anonymous said…
Hello very cool web site!! Man .. Excellent .
. Superb .. I will bookmark your blog and take the feeds additionally?

I am glad to search out a lot of helpful information right here within the post, we'd like work out more strategies on this regard, thanks for sharing. . . . . .

Here is my blog post; madea quotes
Anonymous said…
Hmm it appears like your website ate my first comment (it was extremely long) so
I guess I'll just sum it up what I submitted and say, I'm thoroughly enjoying your blog.
I as well am an aspiring blog blogger but I'm still new to everything. Do you have any helpful hints for newbie blog writers? I'd really appreciate
it.

Feel free to surf to my web blog :: frank ocean quotes
Anonymous said…
I loved as much as you'll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an edginess over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.

Take a look at my web page; future quotes
Anonymous said…
Hey! I just wanted to ask if you ever have any trouble with hackers?

My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup.
Do you have any solutions to prevent hackers?


Here is my page :: e. e. cummings quotes
Anonymous said…
I don't know if it's just me or if everybody else experiencing
issues with your website. It appears like some of the text in your content are running
off the screen. Can someone else please provide feedback and let me know if this is happening to them as
well? This may be a problem with my internet browser because
I've had this happen previously. Appreciate it

Also visit my webpage; unusual animals
Anonymous said…
Wonderful post but I was wondering if you could write a litte more on this subject?
I'd be very thankful if you could elaborate a little bit more. Kudos!

Here is my blog - letting go quotes
Anonymous said…
Aw, this was a really good post. Taking a few minutes and actual effort to
create a really good article… but what can I say… I put things off a whole lot and never manage to get nearly anything done.


Feel free to visit my site - discipline quotes
Anonymous said…
It's ɑwesome to go tŠ¾ see this Ń”eb ѕite and reading the Ī½iews of all colleagurs oon the topic of this paŠ³agraph, while I am also keen of
getting knowledge.

Popular posts from this blog

Cambiando el estado de un checkbox

Cambiando el Estado de un CheckBox Algunas veces deseamos controlar el estado de un checkbox o cambiarlo segĆ¹n determinadas condiciones. Pasos: 1. Creamos un proyecto Web. 2. En el diseƱador agregamos un checkbox y dos botones. * Dar click derecho en el checkbox y luego seleccionar Add Binding Attribute, para agregar los atributos al checkbox, de manera que los podamos usar en nuestro cĆ³digo. Generando automĆ”ticamente private Checkbox checkbox1 = new Checkbox(); public Checkbox getCheckbox1() { return checkbox1; } public void setCheckbox1(Checkbox c) { this.checkbox1 = c; } 3.Damos click derecho en el botĆ³n Habilitar, y seleccionamos Edit Action Event Handler. A continuaciĆ³n, agregamos el cĆ³digo: this.checkbox1.setSelected(true);, el mĆ©todo setSelected con valor true, marca el checkbox como seleccionado, y un valor de false, quita la marca. public String button1_action() { // TODO: Process the action. Return value is a navigation //

Corregir el error el archivo de manifiesto en proyectos maven

Corregir el error en el archivo de manifiesto en proyectos maven Si creamos un proyecto maven con NetBeans e intentamos ejecutarlo encontrarĆ­amos el siguiente error Agregamos el plugin   <artifactId>maven-jar-plugin</artifactId>  <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-jar-plugin</artifactId>                 <version>2.4</version>                 <configuration>                     <archive>                         <manifest>                             <mainClass>org.javscaz.maven1.App</mainClass>                         </manifest>                                           </archive>                 </configuration>             </plugin> Luego al construir el proyecto con dependencias, podemos ejecutar el .jar

Tutorial bƔsico de aplicaciones Web con NetBeans parte 1

NetBeans ofrece un excelente soporte para el desarrollo de aplicaciones Web, en esta ocasiĆ³n lo haremos utilizando el Framework Java Server Faces 2.0. En el Menu Seleccionamos Nuevo->Proyecto y luego en Categorias Java Web y en tipo de Proyectos Web  Application indicamos el nombre del proyecto Seleccinamos el servidor Web, usamos GlassFish ya que este soporta EJB3.0 y JSF 2.0 Framework Java Server Faces El IDE genera el esquelto del proyecto Web Pages   almacenamos las paginas .html, xhtml, jsf, los archivos de recursos, los scripts .js, imagenes Source Packages    Son las clases Java  Test Packages    Son las clases que usamos para los Test Libraries     Tenemos las bibliotecas de Java y GlassFish necesarias para ejecutar la aplicaciĆ³n Web. Test Libraries     EstĆ”n las bibliotecas usadas para los test  Configuration Files    Archivos de configuraciĆ³n de la aplicaciĆ³n. Ejecutamos la aplicaciĆ³n  Esperamos que se inicie GlassFish y se cargue la aplicaciĆ³n Este se