0

I'm trying to write a JUnit test on pessimistic write. My thought is to execute this method within one transaction while running it again in another transaction and trying to modify the element that's returned from the method in the first transaction. I would expect an exception/timeout because the first call should lock the row. I have done something similar to this but the element is modified by the second transaction (testNewTrans method) without hesitation. Is there somewhere I did wrong?

public interface RequestRepository extends CrudRepository<Object, Long> {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select ... ")
    List<Object> findABC(Pageable pageable);
}

in 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
}

in new class

@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");
}
}
Community
  • 1
  • 1
Joseph
  • 97
  • 2
  • 15

1 Answers1

0

Calling testNewTrans() directly from testLock() means it can't be intercepted by spring, therefore the invocation of testNewTrans() ignores any @Transactional (and other) annotations.

If you had autowired a service containing testNewTrans() and called that, you'd see a different effect.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • i probably still not wire it correctly. i am testing it with spring boot and `@DataJpaTest`. Now I put testNewTrans() in a new class as `@component` and `@ComponentScan` to the main class but it is not getting any data. I update the code above. @Kayaman – Joseph Mar 01 '17 at 17:54
  • What do you mean not getting any data? I can imagine this being a tricky situation to test in a single test, as the problem case is inherently related to multiple threads. – Kayaman Mar 02 '17 at 10:10