gpt4 book ai didi

spring - 如何使 DataJpaTest 刷新自动保存?

转载 作者:行者123 更新时间:2023-12-04 01:14:29 24 4
gpt4 key购买 nike

我有一个 Employee具有以下列的实体:

@Entity
class Employee {
@Column(name = "first_name", length = 14)
private String firstName;
我有一个 Spring JPA 存储库:
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
test/resources/application.properties我有以下内容,以便我使用带有自动生成表的内存中 h2 数据库:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
我原以为这个测试会失败,因为 firstName比允许的长:
@DataJpaTest
public class EmployeeRepositoryTest {

@Autowired
private EmployeeRepository employeeRepository;

@Test
public void mustNotSaveFirstNameLongerThan14() {
Employee employee = new Employee();
employee.setFirstName("koraykoraykoray"); // 15 characters!
employeeRepository.save(employee);
}
}
我很惊讶地看到这个测试没有失败,但是以下确实失败了:
@DataJpaTest
public class EmployeeRepositoryTest {

@Autowired
private EmployeeRepository employeeRepository;

@Test
public void testMustNotSaveFirstNameLongerThan14() {
Employee employee = new Employee();
employee.setFirstName("koraykoraykoray"); // 15 characters!
employeeRepository.save(employee);
employeeRepository.findAll();
}
}
使用堆栈跟踪:
Caused by: org.h2.jdbc.JdbcSQLDataException: Value too long for column "FIRST_NAME VARCHAR(14)": "'koraykoraykoray' (15)"; SQL statement:
唯一的区别是第二个测试有额外的 employeeRepository.findAll();声明,据我所知,这会强制 Hibernate 刷新。
这对我来说感觉不对,我更希望测试立即失败 save .
我也可以有
@Autowired
private TestEntityManager testEntityManager;
并打电话
testEntityManager.flush();
但同样,这也感觉不正确..如何在没有任何解决方法或附加语句的情况下使此测试失败?

最佳答案

在您的情况下,最简单的选项是配置 @Transactional注释,强制将测试中的所有更改发送到数据库(它只能在特定的测试中使用):

import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.assertThrows;

@Transactional(propagation = Propagation.NOT_SUPPORTED)
@DataJpaTest
public class EmployeeRepositoryTest {

@Autowired
private EmployeeRepository employeeRepository;

@Test
public void mustNotSaveFirstNameLongerThan14() {
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("koraykoraykoray"); // 15 characters!
assertThrows(DataIntegrityViolationException.class, () -> {
employeeRepository.save(employee);
});
}

@Test
public void mustSaveFirstNameShorterThan14() {
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("koraykor"); // 8 characters!
employeeRepository.save(employee);
}
}
PD:我添加了一个简单的 Integer属性作为 Employee 的 PK实体由于您的存储库定义。
您可以在下图中看到结果:
Reposity tests

关于spring - 如何使 DataJpaTest 刷新自动保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63782195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com