vendredi 22 juin 2018

Hibernate failed test: NonUniqueResultException is not thrown

I'm testing my hibernate dao layer and there is a failed test:

    @Test(expected = NonUniqueResultException::class) // fails
    fun serviceIdByTemplate() {

        val session = em.entityManager.unwrap(Session::class.java)

        session.doWork { connection ->
            val st = connection.createStatement()
            st.execute("create table if not exists SERVICES (s_bp_name varchar(100), s_id varchar(100))")
            st.execute("insert into SERVICES values ('test', '0')") // first row
        }

        val t = dao.serviceIdByTemplate("test")
        assertNotNull(t)
        assertEquals("0", t)
        val t1: String? = dao.serviceIdByTemplate("s")
        assertNull(t1)

        session.doWork {
            val st = it.createStatement()
            st.execute("insert into SERVICES values ('test', '0')") //second row to check exception
        }

        dao.serviceIdByTemplate("test") //exception must be here

    }

I test the dao using org.h2 database. And here is my dao method:

private const val service_id_by_temp = "select t.sId from Services t where t.sBpName = (?) "

fun serviceIdByTemplate(p_name: String): String? {
        return getSession().createQuery(service_id_by_temp)
                .setParameter(0, p_name)
                .uniqueResult() as? String
    }

So I return uniqueResult java docs of says "@throws NonUniqueResultException if there is more than one matching result".

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire