REST Assured can be extended with custom matchers or assertions to tailor validation to specific requirements. Custom matchers can be created using the Hamcrest library, which REST Assured integrates with.
Example :
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class CustomMatchers {
public static TypeSafeMatcher<String> containsSubstring(final String substring) {
return new TypeSafeMatcher<String>() {
@Override
public void describeTo(Description description) {
description.appendText("a string containing ").appendValue(substring);
}
@Override
protected boolean matchesSafely(String item) {
return item.contains(substring);
}
};
}
public static void main(String[] args) {
String response = "This is a sample response";
assertThat(response, containsSubstring("sample"));
}
}?
In this example, a custom matcher
containsSubstring
is created to check if a string contains a specific substring.