当我运行update / delete命令时,JUnit中的单元测试失败

时间:2015-05-04 10:04:17

标签: spring hibernate junit hsqldb

我目前正在使用spring和hibernate在Java中实现API实现。

我的Model包中有两个表

具有OneToMany映射

的User和UserDetail
.item .active {
background-image: url(assets/foo.png);
}

我的API看起来像这样

@Entity
public class User {
    private Long id;
    private String userId;
    private Set<UserDetail> userDetails;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
    public Set<UserDetail> getUserDetails() {
        return userDetails;
    }

    public void setUserDetail(Set<UserDetail> userDetails) {
        this.userDetails = userDetails;
    }
}

@Entity
public class User {
    private Long id;
    private String key;
    private String value;
    private User user;

    @ManyToOne
    @JoinColumn(name = "USER_ID", nullable = false)
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

我已经编写了Junit测试用例来测试用户添加和删除UserDetails,我的addUserDetail正常工作,但是当我调用删除时,更改没有反映出来并且失败了。

以下是我的测试用例

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void addUserDetail(AddUserDetailRequest request) {
    //... adds the user detail for the userId as request.getUserId()
}

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void deleteUserDetail(DeleteUserDetailRequest request) {
    //... deletes a particular value for a user with userId as request.getUserId() and userDetail key as request.getDeleteKey()
}

我正在使用HSQL进行测试

@Test
public void testDeletUserDetail() throws Exception {
    //GIVEN
    String userId = client.newUser().call(getCreateUserRequest()).getId();
    client.newAddUserDetail().call(getAddUserDetailRequest(userId, "key1", "value1"));
    client.newAddUserDetail().call(getAddUserDetailRequest(userId, "key2", "value2"));

    //WHEN
    client.newDeteteUserDetail().call(getDeleteUserDetailRequest(userId, "key2"));

    //THEN
    List<UserDetail> userDetails = client.newGetUserDetail().call(getGetUserDetailRequest(userId));
    assertEquals(userDetails.size(), 1);  // This check fails and says it has a size of 2 instead of 1.
}

我有两个deleteUserDetail实现,其中一个失败。

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.iiitd.myAPI.model" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="database" value="HSQL" />
            <property name="generateDdl" value="true" />
            <property name="showSql" value="false" />
        </bean>
    </property>
</bean>

<jdbc:embedded-database id="dataSource" type="HSQL" />

所有存储库都扩展了JpaRepository

有人能解释如何规避这个问题吗?

任何帮助将不胜感激。

0 个答案:

没有答案