Test DAO in java using Junit4 and Hibernate

2019-08-01 14:40发布

问题:

Testing DAO'm using junit and mainly what I do is start a transaction in hibernate, call the compare function, and then roll back the transaccion.El problem is that if I'm Testing function is a transaction error I can not strip nest, I thought about the idea of ​​implementing DBUnit xml but management does not seem a good idea and less in this instance that I did enough test cases with this method. Anyone have any idea how to fix it without having to use anything other than Junit or hibernate?

This is a example

@Test
public void Test1GetByCodigo(){
    String cod = "999999999";
    DBTenant dbTenant = null; 
    Session sess = null;
    Transaction trans = null;
    ClienteBO cli = null;
    Clientes clie = null;
    try{
        try{
            dbTenant = new DBTenant();
            sess = dbTenant.getTenantSession();
            trans = sess.beginTransaction();
        }
        catch(Exception e){
            fail("Error en la carga de la transaccion.Quedo alguna transaccion abierta?");
        }   
        clie  = CargaCliente(cod);
        sess.save(clie);
        cli = cliBL.getByCodigo(cod);
    }
    catch(Exception e){
        trans.rollback();
        dbTenant.closeSession();
        fail("Error la carga del cliente.Se modifico la bse de datos Clientes??");
    }
    trans.rollback();
    sess.clear();
    dbTenant.closeSession();
    ClienteBO clieEsp = CargaClienteBO(clie);
    assertNotNull(clieEsp);
    assertNotNull(cli);
    assertEquals("Error el cliente no coincide",clieEsp,cli);
}

if cliBL.getbycodigo function () tubiera a transaction would have a bug, thank you for your help thanks

回答1:

Set up an inmemory database for this test using hibernate and let the junit test use transactions as much as it likes. because the database is created before the test and thrown away afterwards there is no problem with isolation. This article might help