【问题标题】:Writing unit test for Pattern annotation为模式注释编写单元测试
【发布时间】:2022-01-17 18:03:55
【问题描述】:
@Data
public class SampleRequest {
    @Valid
    List<someRequest> someReq;

    @NotNull
    @Size(min = 1)
    @Pattern(regexp = "^(https?|http)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]",
            message = "Invalid URL")
    String sampleURL;

    Integer Count;
}

我想为上面的内容编写单元测试来测试我正在使用的注释的 sampleURL,就像我给任何应该匹配正则表达式模式的 URL 一样。我浏览了以下链接how to do unit test validation annotations in springHow to test validation annotations of a class using JUnit?,但它们并没有太大帮助,我也有 setSampleURL 函数。那么如何为 sampleURL 变量编写测试。基本上我想为正则表达式模式编写测试,即我给 sampleURL 的值是否与正则表达式匹配。

【问题讨论】:

    标签: java unit-testing junit


    【解决方案1】:

    使用反射和AssertJ 可能看起来很难看,但是没有 Spring 上下文初始化它又快又简单

        @Test
        void reflection() throws NoSuchFieldException {
            final String url = "https://example.com"; // your URL here for validation
            final String regexp = Arrays.stream(
                    SampleRequest.class.getDeclaredField("sampleURL").getAnnotationsByType(Pattern.class)
                )
                .findFirst()
                .get()
                .regexp();
            Assertions.assertThat(url)
                .as("Ensure that regexp from annotation successfully matched url '%s'", url)
                .matches(regexp);
        }
    

    【讨论】:

    • 这里的 SampleRequest 是什么?
    • 这是描述中你的任务中的一个类
    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多