0
@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;
}

I want to write unit test for the above to test the sampleURL for the annotations that I'm using like if I give any URL it should match to regex pattern. I went through following links how to do unit test validation annotations in spring, How to test validation annotations of a class using JUnit? but they weren't of much help, I have setSampleURL function as well . so how can I write tests for sampleURL variable. Basically I want to write test for the regex pattern, i.e whether the value I am giving to sampleURL matches the regex.

1 Answers1

0

Using reflection and AssertJ it may look ugly, but its fast and simple without Spring context initialization

    @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);
    }
lazylead
  • 1,453
  • 1
  • 14
  • 26