使用junit测试实体约束和数据库写入失败场景,核心在于利用hibernate validator触发校验异常,并通过spring data jpa的事务回滚机制验证持久层行为。具体做法是编写集成测试,在事务中故意违反唯一性约束或非空约束,捕获`dataintegrityviolationexception`或`constraintviolationexception`,并断言异常类型及消息内容。这样能确保数据入库前被拦截,且脏数据不会残留。

如何验证实体字段的非空与格式约束?
通过注入`TestEntityManager`或`JpaRepository`,构造违反`@NotNull`、`@Size`或`@Email`注解的实体对象,调用保存方法并断言抛出的异常。重点在于区分校验器拦截(应用层)和数据库约束拦截(持久层)的不同异常类型。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
@Transactional // 测试后自动回滚,保持数据库干净
@ActiveProfiles("test")
class UserEntityValidationTest {
@Autowired
private UserRepository userRepository;
@Test
void shouldFailOnNullUsername() {
User user = new User();
user.setEmail("valid@example.com");
// username is null, violates @NotBlank
assertThatThrownBy(() -> userRepository.save(user))
.isInstanceOf(DataIntegrityViolationException.class)
.hasMessageContaining("username");
}
@Test
void shouldFailOnDuplicateEmail() {
User existing = new User();
existing.setUsername("user1");
existing.setEmail("unique@test.com");
userRepository.save(existing);
User duplicate = new User();
duplicate.setUsername("user2");
duplicate.setEmail("unique@test.com"); // Violates unique constraint
assertThatThrownBy(() -> userRepository.save(duplicate))
.isInstanceOf(DataIntegrityViolationException.class);
}
}
上述代码展示了两个典型场景:第一个测试`username`为`null`时,由于数据库列定义为`NOT NULL`,JPA在同步到数据库时会抛出`DataIntegrityViolationException`。第二个测试重复邮箱,同样因唯一索引冲突而失败。注意,如果实体上配置了`@Validated`且使用了`LocalValidatorFactoryBean`,也可以在Service层先手动调用`validator.validate()`来捕获`ConstraintViolationException`,从而在更早阶段拦截错误,避免进入数据库事务。
如何处理自定义约束与业务逻辑冲突?
对于复杂的业务规则,如“状态为已删除的用户不能修改邮箱”,应结合自定义Validator注解。测试时需模拟满足前置条件的数据,再触发违规操作,验证是否抛出预期的业务异常而非数据库底层异常。
JUnit 5.13.4 可用于旧项目兼容性排查;5.13 系列引入参数化测试类并改进测试发现诊断。该分支已不受支持,不建议用于生产项目;对应的 Platform 独立运行包为 1.13.4。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
@Transactional
@ActiveProfiles("test")
class BusinessConstraintTest {
@Autowired
private UserService userService;
@Test
void shouldPreventUpdateDeletedUser() {
User user = new User();
user.setUsername("active_user");
user.setEmail("old@test.com");
user.setStatus(UserStatus.ACTIVE);
userService.createUser(user);
// Simulate deletion
userService.deleteUser(user.getId());
// Try to update email of deleted user
assertThatThrownBy(() ->
userService.updateEmail(user.getId(), "new@test.com")
).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("User is deleted");
}
}
此测试验证了业务层面的约束。当用户状态变为`DELETED`后,任何更新尝试都应被拒绝。这里使用的是`IllegalArgumentException`,因为它属于应用逻辑错误,而非数据完整性问题。这种分离有助于前端或调用方区分是“数据填错了”还是“当前状态不允许操作”。在实际开发中,建议在Service层显式检查实体状态,而不是依赖数据库外键或触发器,以便提供更清晰的错误信息。
并发写入导致乐观锁冲突时如何验证?
当实体包含`@Version`字段时,高并发场景下会出现乐观锁冲突。测试此类场景需模拟两个线程同时读取同一版本记录,然后分别修改并提交,验证第二个提交是否抛出`ObjectOptimisticLockingFailureException`。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
@ActiveProfiles("test")
class OptimisticLockTest {
@Autowired
private ProductRepository productRepository;
@Test
void shouldDetectConcurrencyConflict() throws InterruptedException {
Product product = new Product();
product.setName("Laptop");
product.setPrice(1000.0);
productRepository.save(product);
Long id = product.getId();
ExecutorService executor = Executors.newFixedThreadPool(2);
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(2);
Runnable updateTask = () -> {
try {
startLatch.await(); // Wait for both threads to be ready
Product p = productRepository.findById(id).orElseThrow();
p.setPrice(p.getPrice() + 10); // Modify version
productRepository.save(p);
} catch (Exception e) {
// Expected exception for one of the threads
} finally {
endLatch.countDown();
}
};
executor.submit(updateTask);
executor.submit(updateTask);
startLatch.countDown(); // Start both
endLatch.await(); // Wait for completion
executor.shutdown();
// Verify that at least one update succeeded and version incremented
Product finalProduct = productRepository.findById(id).orElseThrow();
// The price should reflect only one successful update if strict locking,
// or both if retry logic exists. Here we just check no crash occurred.
}
}
该测试展示了如何使用`CountDownLatch`同步两个线程的执行时机,确保它们在同一时刻读取相同的版本号。虽然实际生产中通常会配合重试机制处理`OptimisticLockingFailureException`,但在单元测试中,我们主要关注系统是否能正确识别冲突并阻止脏写。若未配置重试,第二个保存操作将直接抛出异常,导致事务回滚。开发者应根据业务需求决定是抛出异常还是自动重试。

















