Test DAO in java using Junit4 and Hibernate

不想你离开。 提交于 2019-12-24 08:35:10

问题


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



来源:https://stackoverflow.com/questions/12916014/test-dao-in-java-using-junit4-and-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!