单元测试Hibernate POJO [英] Unit testing Hibernate POJO

查看:51
本文介绍了单元测试Hibernate POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要进行单元测试的休眠POJO.它看起来类似于:

I have a hibernate POJO that I want to unit test. It looks similar to this:

public class MyPojo{
    private final Integer someIntData;

    private MyPojo(){
        //Just to satisfy compiler, hibernate will override
        someIntData = null;
    }

   //Methods etc...
}

我想对该类进行单元测试,但实际上并不想创建一个新的构造函数,而只是手动设置"someIntData".是否有一种快速简便的方法来使休眠实例化MyPojo的测试实例而无需模拟数据库呢?

I'd like to unit test this class, but don't really want to make a new constructor just to set 'someIntData' manually. Is there a quick and easy way to get hibernate to instantiate a test instance of MyPojo without mucking around with a mock database?

推荐答案

私有构造函数意味着您正在提供一个"builder"方法来替换该构造函数(通常用于不可变的实例),或者该类永远都不打算初始化完全没有.在后一种情况下,通常是因为该类是单例,并且您将提供一个返回单个实例的方法.

Private constructor means that you are either providing a "builder" method to replace the constructor (usually for immutable instances) or that the class is never meant to be initialized at all. In the later case, its usually because the class is meant to be a singleton and you'd provide a method which returns the single instance.

Hibernate不会抱怨它,因为它使用反射来消耗此构造函数.由于您不应该为测试提供特殊代码,因此我看到的唯一解决方案是使用反射实例化一个新的POJO.

Hibernate does not complain about it because it uses reflection to consume this constructor. As you are not supposed to provide special code for a test, the only solution I see is to use reflection to instantiate a new POJO.

但是我真的认为您应该重新考虑并提供一个builder方法,接受构建新实例所需的参数.

But I really think you should reconsider and provide a builder method, accepting the parameters needed to build a new instance.

这篇关于单元测试Hibernate POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆