【问题标题】:How can i test Optmistic Locking using junit, spring and JPA?如何使用 junit、spring 和 JPA 测试 Optmistic Locking?
【发布时间】:2015-01-08 13:15:57
【问题描述】:

我的实体带有 @version 列、daos 和 junit 测试。 如何在 junit 测试用例中引发乐观锁异常,以查看它是否被正确处理?

我使用的是spring transaction managamnt,所以我认为这让它变得更加复杂

【问题讨论】:

    标签: spring jpa junit


    【解决方案1】:
    1. 从 jUnit 测试方法打开事务并从某个表中读取一行。
    2. 创建一个新线程并打开另一个将读取同一行的数据库事务。
    3. 更新它,并将其保存到数据库中。
    4. 暂停 jUnit 测试方法使用的主线程。
    5. 修改开头读取的数据并尝试更新行。因此,应该抛出一个乐观锁异常。

    【讨论】:

    • 忘了说我正在使用 spring TX managamanent,现在已编辑。 tx 管理可以吗?
    • 是的,当然,要打开数据库事务,您需要一些 TX 管理。请记住,不可能从同一个线程打开两个单独的事务。
    【解决方案2】:

    在我当前的项目中,我们必须处理 OptimisticLockException 并将其包装到自定义异常中。我们使用的是休眠而不是 Spring。但也许这种方式会对你有所帮助。

    对于我的解决方案,您的测试中需要一个 OpenEJB 容器:

    @LocalClient
    public class ExampleClassTest {
    
        //its a self written class to bootstrap the open ejb container
        private static OpenEjbContainerStarter openEjbStarter;
    
        private static Context context;
    
        @Resource
        private UserTransaction userTransaction;
    
        @EJB
        private ExampleWithSaveActionFacade facade;
    
        @EJB
        private ExampleDAO exampleDataAccessObject;
    
        @BeforeClass
        public static void setUpBefore() throws Exception {
            openEjbStarter = new OpenEjbContainerStarter();
            context = openEjbStarter.startOpenEJB();
        }
    
        @AfterClass
        public static void shutdown() throws NamingException, SQLException {
            openEjbStarter.destroyOpenEJB();
        }
    
        @Before
        public void before() throws Exception {
            context.bind("inject", this);
        }
    
        @Test(expected = OptimisticLockException.class)
        public void testSaveSomethingWithException(){
    
            //get the first object you will manipulate and change the Version
            //current Version is 1
            ExampleModel example = exampleDataAccessObject.findById(1L);
            example.setSomeData("test");
    
            //get the second object what will cause the exception
            //current version is 1
            ExampleModel exampleOldObject = exampleDataAccessObject.findById(1L);
    
            // returnValue with the version number 2
            ExampleModel returnValue = facade.persistOrUpdateUser(example);
    
            //try to save the object with the version 1
            //throws the OptimisticLockException
            facade.persistOrUpdateUser(exampleOldObject);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2012-10-24
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多