在 Spring Junit 测试中,我如何使用默认回滚=true 测试级联操作



这是我的示例测试用例,其中 A 与 B 具有一对多关系。现在,我将 B 的实例添加到 Bs A 的列表中,并对 A 的实例执行 SaveOrUpdate,但是当回滚为 true 时测试用例失败,因为未生成 B 实例的 ID。当回滚为 false 时,它会通过,但随后也会将条目添加到数据库中。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    TransactionalTestExecutionListener.class,DbUnitTestExecutionListener.class})
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
@Transactional(propagation=Propagation.REQUIRED)
public class Test1 {
    @Autowired
    DummyDao dummyDao;
    @Test
//  @Rollback(false)
    public void newTest2(){
        //      A temp=dummyDao.getAById(new Long(1));
        A temp=dummyDao.getAs().get(0);
        Hibernate.initialize(temp.getBs());
    B class2=new B();
    temp.getBs().add(class2);
    dummyDao.saveA(temp);
    assertNotNull(class2.getId());
}
}

A类详情

import java.util.List;  
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.IndexColumn;
@Table(name="UJJWAL_DUMMY", schema="dbo")
@Entity
public class A {
    @Id
    @Column
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column
private String prop;
@OneToMany(fetch=FetchType.LAZY)
@Cascade({CascadeType.ALL})
@JoinColumn(name="fk_A")
@IndexColumn(name="idx")
private List<B> Bs;
// Setter and getters
}

B类详情 @Entity 公共类 B {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column
private Long id;
@Column
private String dummyColumn2;
// Setters and Getters
}

您是否尝试在检查 ids 值之前手动刷新对数据库的更改?如果在数据库中生成了 id,则需要在设置之前进行刷新。 @GeneratedValue(strategy=GenerationType.AUTO)通常默认为身份类型的列,这是数据库中自动生成的编号。

相关内容

最新更新