【问题标题】:Entity is not deleted in a JUnit test with @Transactional在使用 @Transactional 的 JUnit 测试中未删除实体
【发布时间】:2019-11-16 16:46:13
【问题描述】:

我有时会在我的 JUnit 测试中使用 @Transactional 注释。我在 JUnit 中使用 @Transactional 来延迟获取集合。

目前,我遇到了 @Transactional 注释的未知行为。

在我的数据库中,我有一个 Car 实体。我在测试中删除了这个实体。如果我在测试中使用 @Transactional,则该实体不会从数据库中删除。 否则,如果我不使用 @Transactional 则实体将被删除。 我在数据库中的每次测试后都会看到这一点。

我有标准实体和存储库。 我的实体:

@Entity 
public class Car {

    @Id
    @GeneratedValue
    private int id;

    private String model;

    //...constructors, getters and setters }

我的仓库:

public interface CarRepository extends JpaRepository<Car, Integer>{
    List<Car> findByModel(String mazda);
}

我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RelationsTest {

    @Autowired
    CarRepository carRepository;

    @Test
    //@Transactional
    public void deleteCar() throws Exception {

        List<Car> cars = carRepository.findByModel("Mazda");
        assertThat(cars).hasSize(1);

        carRepository.deleteById(cars.get(0).getId());

    }

@Transactional 实体没有从数据库中删除的原因是什么?

【问题讨论】:

    标签: java junit transactions spring-data-jpa


    【解决方案1】:

    来自 Spring Boot documentation

    如果你的测试是@Transactional,它默认在每个测试方法结束时回滚事务。

    【讨论】:

    • 好的。让我看看……等一下。
    猜你喜欢
    • 2016-04-24
    • 2022-01-23
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2012-05-29
    • 2015-12-29
    相关资源
    最近更新 更多