1

I'm trying to testing this code in junit 4 and java 8 (I can't improve the version).

The thing is, I can't use in this version @MockBean or @Autowired for test coding, so, ¿what's the better option if I can't improve the version?

Code:

public class DaoHibernate extends BaseDaoHibernate implements Dao {

private static final String ID_CD_QUERY_PARAM = "idCD";
private static final String IDPAIS_QUERY_PARAM = "idPais";
/**
 * Instancia del logger
 */
private static final Logger LOGGER = LoggerFactory.getLogger(DaoHibernate.class);
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");



public List<Combo> getThingsByCamion (Integer idCD, Date fDesde,Date fHasta, Integer idPais,String idReferenciaTransporte){
    try {
        List<Combo> things = new ArrayList<Combo>();

        if (idCD != null) {

            final StringBuilder hqlQueryThings = new StringBuilder();

            hqlQueryThings.append("SELECT DISTINCT ");
            hqlQueryThings.append(" ao.referencia ");
            hqlQueryThings.append(" FROM ");
            hqlQueryThings.append(" almacen.agrupacion_operativa ao, ");
            hqlQueryThings.append(" almacen.Detalle_Agrupacion_Operativa dao, ");
            hqlQueryThings.append(" almacen.detalle_envio_exportacion dee, ");
            hqlQueryThings.append(" almacen.seguimiento_bulto sb ");

            if(idPais!=null ){
                hqlQueryPallet.append(" INNER JOIN MAESTROS.LOCALIZACION LOC ON LOC.ID_LOCALIZACION = sb.id_localizacion_destino ")
                .append(" AND LOC.ID_PAIS = :idPais ");
            }

            hqlQueryThings.append(" WHERE ");
            hqlQueryThings.append(" ao.id_agrupacion_operativa = dao.id_agrupacion_operativa AND ");
            hqlQueryThings.append(" sb.id_localizacion_origen = :idCD AND ");
            hqlQueryThings.append(" dee.id_bulto = dao.id_bulto  ");

            if(idReferenciaTransporte!=null ){
                hqlQueryPallet.append("  AND dee.referencia_transporte = :idReferenciaTransporte ");
            }
            if(fDesde!=null && fHasta!=null){
                hqlQueryThings.append("  AND SB.Fecha_Expedicion >= :fDesde AND ");
                hqlQueryThings.append("  SB.Fecha_Expedicion <= :fHasta ");
            }

            hqlQueryThings.append(" WITH UR ");
            final Query queryThing = getHibernateTemplate().getSessionFactory().getCurrentSession()
            .createSQLQuery(hqlQueryPallet.toString());
            if (idPais != null) {
                queryThing.setInteger(IDPAIS_QUERY_PARAM, idPais);
            }
            if (idReferenciaTransporte != null) {
                queryThing.setString("idReferenciaTransporte", idReferenciaTransporte);
            }
            queryThing.setInteger(ID_CD_QUERY_PARAM, idCD);
            queryThing.setDate("fDesde", fDesde);
            queryThing.setDate("fHasta", fHasta);

            final List<String> result = (List<String>) queryThing.list();

            if (result != null) {

                for(String obj : result){
                    Combos c = new Combos();
                    c.setKey(obj);
                    c.setValue(obj);

                    pallets.add(c);
                }
            }
        }
        LOGGER.debug("Fin getThingsByCamion");
        return pallets;
    } catch (final RuntimeException recep) {
        LOGGER.error("Errorejecutando getThings", recep);
        throw recep;
    }
}

When I arrive to final Query queryThing = getHibernateTemplate().getSessionFactory().getCurrentSession() .createSQLQuery(hqlQueryPallet.toString()); it just says NullPointerException because it can't find the current session in the test.

The Test:

public class DaoHibernateTests {

private static final String ORIGEN = "Origen";
private static final String MATRICULA = "Matricula";
private static final String CODIGO_ENVIO = "Envio";

private static final String PLATAFORMA = "Plataforma 1";
private static final Integer ID_PLATAFORMA = 1;

/** The sdf. */
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

private DaoHibernate daoHibernate;
private Date fechaEnvio;

@Before
public void setUp() throws ParseException {

    fechaEnvio = sdf.parse("01-01-2021");

    daoHibernate = new AgrupacionOperativaDaoHibernate();
}

@Test(expected = NullPointerException.class)
public void buscarMercanciaEntradaTestError1() {
    List<Combo> getThingsByCamion = daoHibernate.getThingsByCamion(1, fechaEnvio,fechaEnvio, 1,CODIGO_ENVIO);

    Assert.assertEquals(1, getThingsByCamion.size());
}

POM: Dependencies for testing:

<java.version>1.8</java.version>
    <junit.version>4.4</junit.version>    

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>3.1.0</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.1.0</version>
        <type>pom</type>
    </dependency>

What I need to do?

Thanks!

1 Answers1

0

You're already using Java 8, so that's not a reason for not using JUnit 5. That means you can use both JUnit 5 and the JUnit 4 functionality and packages. Do that by using the JUnit 5 dependencies (I suggest junit-jupiter and not junit-jupiter-api, as the former comes with junit-jupiter-engine and junit-jupiter-params) as well as the vintage engine (junit-vintage-engine).

This allows you to keep using JUnit 4 (actually the vintage engine) for all existing tests, and JUnit 5 for this new test.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20
  • So you, mean to keep junit version in 4.4 but using those dependencies that you tell me the lastest right? Because, I could, but in this project it won't let me change the 4.4 junit version – DaMostWanted13 Feb 04 '22 at 12:59
  • No, I meant replace the current JUnit 4.4 dependency with both `junit-jupiter` and `junit-vintage-engine`. The latter should make sure your existing tests still work. However, if you're not even allowed to change the 4.4 version that won't work of course. Can you tell us the reason why you must use this exact version? – Rob Spoor Feb 04 '22 at 13:04
  • I must to use it because of the project, I mean, its a antique java project and they don't use the newest, because if the new version broke the service. I am more familiar with junit 5, and using @Mockbean or when().thenReturn, but I can't do it because it doesn't find the class. And I ask you, 4.4 you say to remove this, and put vintage and jupitar the latest right? – DaMostWanted13 Feb 04 '22 at 13:22
  • That's what I would try at least. It shouldn't break your existing tests because the vintage engine should work exactly like JUnit 4. – Rob Spoor Feb 04 '22 at 13:38
  • Okey, I try it, but I think that @MockBean it works only with @RunWith(SpringRunner.class) as I see, and if I use MockitoJUnitRunner it says to upgrade to junit 4.5 – DaMostWanted13 Feb 04 '22 at 13:41
  • @MockBean also works with the Spring extension. You'll need to replace runners with extensions for this test (but not the others). – Rob Spoor Feb 04 '22 at 13:49