繁体   English   中英

如何在不依赖数据库的情况下将JUnit测试应用于我的Insert(),update(),delete()方法(使用Mockito)

[英]How can I apply JUnit tests to my Insert(),update(),delete() methods without database dependency (with Mockito)

我将向我的方法发送一个实体作为它们的参数,这意味着我已经有了要从数据库中插入,更新或删除的信息。 我用我的持久性单元名称注入了entitymanager,所以我知道它可以工作,我的entitymanager的名称是“ em”。 我使用数据库连接从数据库映射了我的类,正在使用的类由“ TipoUsuario”命名。这是我的方法:

public void insert(TipoUsuario tipoUsuario) throws Exception {
    if (em != null) {
        em.persist(tipoUsuario);
    }
}

public void update(TipoUsuario tipoUsuario) throws Exception {
    if (em != null) {
        em.merge(tipoUsuario);
    }

}

public void delete(TipoUsuario tipoUsuario) throws Exception {
    if (em != null) {
        em.remove(tipoUsuario);
    }
}

我正在研究第一个方法(插入),但是我不知道如何测试我的方法...这是我测试插入方法的方法:

@Test
public void testInsert() throws Exception {
    System.out.println("insert");
    TipoUsuario tipoUsuario = new TipoUsuario(1, "Mantenedor", "AC2354", true);
    //Instance of my class where I have my insert, update and delete methods
    Utilidades instance = new Utilidades();
    //I mock an entity manager with annotation @Mock and I pass that mocked entitytmanager to my the entitymanager that I have in my main class 
    instance.em = this.em;
    //and that's all i got.. I don't know how to test if it really works
    //i send my entity to my methor insert
    instance.insert(tipoUsuario);
    //i dont know what is return o how to use the assertEquals in this case...
    assertEquals( ?,  ?);
}

我嘲笑了entitymanager,因为那不是我的代码的一部分,并且我知道其他人以前已经测试过,我唯一要测试的是我的方法是否将信息插入数据库中。

如果您有任何想法,我将不胜感激。

您可以使用

Mockito.verify(em, Mockito.times(1)).persist(tipoUsuario);

查看persist方法是否被调用过1次。

我嘲笑了entitymanager,因为那不是我的代码的一部分,并且我知道其他人以前已经测试过,我唯一要测试的是我的方法是否将信息插入数据库中。

如果实体管理器是模拟的,则对其的方法调用不是真实的,因此不会对数据库进行真实的更新。 正如Charles回答的那样,您只能验证一次确实调用过该方法,并且只能调用一次,但是如果嘲笑了实体管理器,则对我来说验证数据是没有意义的。

作为单元测试的一部分进行实时插入(或任何实际的db调用)是不可取的,因为单元测试通常在构建时运行,并且那时可能没有可用的DB。 如果单元测试失败意味着您的构建失败,那么您将遇到麻烦。

如果您确实希望这样做,请尝试在单元测试的上下文中使用一些内存数据库来完成测试。

另外,您要完成的工作可能属于集成测试而不是单元测试-请考虑这些原则。

如果您真的对JPA / DAO /数据层的单元测试感兴趣,请查看Apache DBUnit和其他一些类似的框架。

关于DbUnit

JPAUnit-在JPA单元测试中替代DBUnit

单元测试JPA ...停止集成测试!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM