代码之家  ›  专栏  ›  技术社区  ›  Thom

如何重写单元测试的insertable=false

  •  0
  • Thom  · 技术社区  · 8 年前

    我是我们应用程序中另一个系统上的一个客人,我不想做任何大规模的改变。

    我正在从头开始写一个单元测试,因为前一个作者并不费心。(抱怨)我正试图插入一行来测试我的JPA/hibernate查询,但很惊讶我得到了以下错误:

    javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_14316 table: OPTIONVALUE column: OPTION_INDEX
    
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1306)
        at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:989)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:293)
        at com.sun.proxy.$Proxy109.flush(Unknown Source)
    

    尤其是当我知道我已经设置了这个值,因为我必须为它编写一个setter。然后,在其中一个对象上,我找到了以下定义(我必须查找它):

    public static final String OPTION_VALUE_POSITION_COLUMN = "option_index";
    @Column(name = OPTION_VALUE_POSITION_COLUMN, insertable = false, updatable = false, nullable = false)
    private int position;
    

    所以这就解释了为什么我在那个列上仍然是空的。

    所以,我的问题是,有没有一种方法可以在单元测试中覆盖它。我试着在google上搜索了一些东西,但是这个短语有点问题,我没有找到任何东西。

    1 回复  |  直到 8 年前
        1
  •  0
  •   coladict    8 年前

    1. 测试类(如果正在运行测试)
    2. 主要资源
    3. 测试依赖jar(如果正在运行测试)

    你可以这样检查:

    // I have yet to run into a custom ClassLoader that does not extend URLClassLoader
    URLClassLoader urls = (URLClassLoader) getClass().getClassLoader();
    for (URL url : urls.getURLs()) {
        System.out.println(url);
    }
    

    不过,这有点问题。Hibernate的类加载器可能(或可能不会)从测试中读取重写的类,除非您有配置文件 persistence.xml orm.xml 列出所有需要扫描的类。你不能依赖 <exclude-unlisted-classes>false</exclude-unlisted-classes>