有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有一种方法可以预期超时?

目前,我正在编写一些集成测试,我需要断言对方法的调用至少会阻止调用线程x秒。问题是,我有一个方法将永远阻止,我需要声明它已被阻止至少x秒。有办法吗?唯一的另一个答案是关于JUnit4的,我们正在使用JUnit5。。。提前谢谢你的回答


共 (2) 个答案

  1. # 1 楼答案

    最后,我选择了不同的策略。您可以看到,我的用例是测试一些JDBCPostgres事务是否会阻塞。相反,我将只等待事务超时开始,并断言从测试开始到超时触发之间的时间。谢谢大家抽出宝贵的时间回答我的问题

  2. # 2 楼答案

    您可以使用assertTimeout(Duration timeout, Executable executable)解决您的问题。有关更多信息,请访问JUnit 5 User Guide

        @Test
        void timeoutNotExceeded() {
            // The following assertion succeeds.
            assertTimeout(ofMinutes(2), () -> {
                // Perform task that takes less than 2 minutes.
            });
        }
    
        @Test
        void timeoutNotExceededWithResult() {
            // The following assertion succeeds, and returns the supplied object.
            String actualResult = assertTimeout(ofMinutes(2), () -> {
                return "a result";
            });
            assertEquals("a result", actualResult);
        }
    
        @Test
        void timeoutNotExceededWithMethod() {
            // The following assertion invokes a method reference and returns an object.
            String actualGreeting = assertTimeout(ofMinutes(2), AssertionsDemo::greeting);
            assertEquals("Hello, World!", actualGreeting);
        }
    
        @Test
        void timeoutExceeded() {
            // The following assertion fails with an error message similar to:
            // execution exceeded timeout of 10 ms by 91 ms
            assertTimeout(ofMillis(10), () -> {
                // Simulate task that takes more than 10 ms.
                Thread.sleep(100);
            });
        }
    
        @Test
        void timeoutExceededWithPreemptiveTermination() {
            // The following assertion fails with an error message similar to:
            // execution timed out after 10 ms
            assertTimeoutPreemptively(ofMillis(10), () -> {
                // Simulate task that takes more than 10 ms.
                new CountDownLatch(1).await();
            });
        }