0
我试图写悲观写入的JUnit测试。我的想法是在一个事务中执行此方法,同时在另一个事务中再次运行此方法,并尝试修改第一个事务中从该方法返回的元素。我会期待一个异常/超时,因为第一次调用应该锁定该行。我做了类似于this的一些事情,但元素被第二个事务(testNewTrans方法)毫不犹豫地修改。有什么地方我做错了吗?Spring Data上的LockModeType.PESSIMISTIC_WRITE
public interface RequestRepository extends CrudRepository<Object, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select ... ")
List<Object> findABC(Pageable pageable);
}
在新类的junit
@RunWith(SpringRunner.class)
@DataJpaTest
@TransactionConfiguration(defaultRollback = true)
public class RepositoryTest {
@Configuration
@ComponentScan("test.package")
@ContextConfiguration
public static class SpringConfig {
}
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testLock() throws InterruptedException {
List<Object> requests1 = requestRepository.findABC(new PageRequest(0, 2));
test22.testNewTrans(); // return empty list
}
@Component
public class Test22 {
private final RequestRepository requestRepository;
public Test22(RequestRepository requestRepository) {
this.requestRepository = requestRepository;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
private void testNewTrans() {
List<Object> requests2 = requestRepository.findABC(new PageRequest(0, 2));
Object aa = requests2.get(0);
System.out.println("=============>" + aa);
aa.setSomething("abc");
}
}
我可能仍然没有正确连线。我正在用spring引导和'@ DataJpaTest'测试它。现在,我将testNewTrans()放在一个新的类中,作为“@ component”和“@ ComponentScan”放到主类中,但它没有获取任何数据。我更新了上面的代码。 @Kayaman – Joseph
你的意思是没有得到任何数据?我可以想象这是一个棘手的情况在单个测试中进行测试,因为问题案例与多线程有内在关联。 – Kayaman