使用junit拦截并Assert私有异常

r3i60tvu  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(140)

有多个问题与我的类似,但有一点不同,我想捕获私有内部异常(如果这是准确的定义),然后Assert它。我在下面做了测试。我正在寻找类似的方法之一是斯波克thrown()。提前感谢您的帮助。我对junit没有太多的经验,如果这对你来说微不足道,请回答或链接页面,这可能会帮助我理解。
感谢您的帮助和支持!:D
例外reactor.core.Exceptions$RetryExhaustedException

public abstract class Exceptions {

    static final class RetryExhaustedException extends IllegalStateException {

        RetryExhaustedException(String message) {
            super(message);
        }

        RetryExhaustedException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}

我的测试

@Test
    void exampleTest() {
        // given:
        stubToForce5xxResponse();

        // when:
        var ex = getExceptionThrown(() -> exampleService.exampleMethod());

        // then:
        Assertions.assertThat(ex).isNotNull();
        Assertions.assertThat(ex.getClass().getName()).isEqualTo("reactor.core.Exceptions$RetryExhaustedException");
        Assertions.assertThat(ex.getMessage()).isEqualTo("Retries exhausted: 3/3");
    }

    private Throwable getExceptionThrown(Runnable runnable) {
        try {
            runnable.run();
            return null;
        } catch (Exception ex) {
            return ex;
        }
    }
gcuhipw9

gcuhipw91#

给出你的示例代码,我假设你使用AssertJ:

@Test
void exampleTest() {
    stubToForce5xxResponse();

    assertThatThrownBy(() -> exampleService.exampleMethod())
        .isInstanceOfSatisfying(IllegalStateException.class, ex -> {
            assertThat(ex.getClass().getName()).isEqualTo("reactor.core.Exceptions$RetryExhaustedException");
            assertThat(ex).hasMessage("Retries exhausted: 3/3");
        });
}

如果你想坚持JUnit JupiterAssert:

@Test
void exampleTest() {
    stubToForce5xxResponse();

    var ex = assertThrows(IllegalStateException.class, () -> exampleService.exampleMethod());

    assertEquals("reactor.core.Exceptions$RetryExhaustedException", ex.getClass().getName());
    assertEquals("Retries exhausted: 3/3", ex.getMessage());
}

(Note AssertJ是asserThat(actual).isEqualTo(expected),而JUnit Jupiter是assertEquals(expected, actual)

相关问题