Best junit code snippet using org.hamcrest.FeatureMatcher.matchesSafely
Source:IoMatchers.java
...48 .appendText(Arrays.toString(files))49 .appendText(" or is not a directory");50 }51 @Override52 protected boolean matchesSafely() {53 files = MoreObjects.firstNonNull(value().list(), new String[0]);54 return files.length == numberOfFiles;55 }56 };57 }58 public static Matcher<File> fileWithName(String filename) {59 return new ValueCachingMatcher<File>() {60 @Override61 public void describeTo(Description description) {62 description.appendText("file with name " + filename);63 }64 @Override65 protected void describeMismatchSafely(File item, Description mismatchDescription) {66 mismatchDescription.appendText("file ").appendValue(item).appendText(" did not have name " + filename);67 }68 @Override69 protected boolean matchesSafely() {70 return value().getName().equals(filename);71 }72 };73 }74 public static Matcher<File> fileContainingString(String contents) {75 return fileWithConents(containsString(contents));76 }77 public static Matcher<String> matchingPattern(String patternStr) {78 return new TypeSafeDiagnosingMatcher<String>() {79 @Override80 protected boolean matchesSafely(String text, Description mismatchDescription) {81 Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL);82 boolean matches = pattern.matcher(text).matches();83 if (!matches) {84 mismatchDescription.appendText(text);85 }86 return matches;87 }88 @Override89 public void describeTo(Description description) {90 description.appendText("matching '" + patternStr + "'");91 }92 };93 }94 public static Matcher<File> fileWithConents(Matcher<String> contentsMatcher) {95 return new FeatureMatcher<File, String>(contentsMatcher, "file contents", "file contents") {96 @Override97 protected String featureValueOf(File file) {98 try {99 return FileUtils.readFileToString(file, StandardCharsets.UTF_8);100 } catch (IOException e) {101 throw new RuntimeException(e);102 }103 }104 };105 }106 public static Matcher<File> fileExists() {107 return new ValueCachingMatcher<File>() {108 @Override109 public void describeTo(Description description) {110 description.appendText("file ").appendValue(value()).appendText(" to exist");111 }112 @Override113 protected void describeMismatchSafely(File item, Description mismatchDescription) {114 mismatchDescription115 .appendText("file ")116 .appendValue(item.getAbsolutePath())117 .appendText(" did not exist");118 }119 @Override120 protected boolean matchesSafely() {121 return value().exists();122 }123 };124 }125 public static Matcher<File> isDirectory() {126 return new ValueCachingMatcher<File>() {127 @Override128 public void describeTo(Description description) {129 description.appendValue(value()).appendText(" is directory");130 }131 @Override132 protected void describeMismatchSafely(File item, Description mismatchDescription) {133 mismatchDescription.appendValue(item.getAbsolutePath()).appendText(" is not a directory");134 }135 @Override136 protected boolean matchesSafely() {137 return value().isDirectory();138 }139 };140 }141 public static Matcher<Path> pathFileExists() {142 return new ValueCachingMatcher<Path>() {143 @Override144 public void describeTo(Description description) {145 description.appendText("file ").appendValue(value()).appendText(" to exist");146 }147 @Override148 protected void describeMismatchSafely(Path item, Description mismatchDescription) {149 mismatchDescription.appendText("file ").appendValue(item).appendText(" did not exist");150 }151 @Override152 protected boolean matchesSafely() {153 return value().toFile().exists();154 }155 };156 }157}...
Source:StateMatchers.java
...22 "state with top of operand stack matching ")23 .appendDescriptionOf(expectedMatcher);24 }25 @Override26 protected boolean matchesSafely(final JState item,27 final Description mismatchDescription) {28 final Object operand = item.peekOperand();29 mismatchDescription.appendText("state with top of operand stack ");30 expectedMatcher.describeMismatch(operand, mismatchDescription);31 return expectedMatcher.matches(operand);32 }33 };34 }35 public static Matcher<? super JState> instructionEqual(final Instruction expectedInstruction) {36 return new TypeSafeDiagnosingMatcher<JState>(JState.class) {37 @Override38 public void describeTo(final Description description) {39 description.appendText("state with next instruction equal to ")40 .appendValue(expectedInstruction);41 }42 @Override43 protected boolean matchesSafely(final JState item,44 final Description mismatchDescription) {45 final Instruction instruction = item.instruction();46 mismatchDescription.appendText("state with next instruction ")47 .appendValue(instruction);48 return equalTo(expectedInstruction).matches(instruction);49 }50 };51 }52 public static Matcher<? super JState> terminalInstruction() {53 return new TypeSafeDiagnosingMatcher<JState>(JState.class) {54 @Override55 public void describeTo(final Description description) {56 description.appendText("instruction with no successor");57 }58 @Override59 protected boolean matchesSafely(final JState item,60 final Description mismatchDescription) {61 final Instruction instruction = item.instruction();62 mismatchDescription.appendText("instruction with successor ")63 .appendValue(instruction);64 return !instruction.hasNext();65 }66 };67 }68 public static Matcher<? super JState> stackSize(final int expectedSize) {69 return new TypeSafeDiagnosingMatcher<JState>(JState.class) {70 @Override71 public void describeTo(final Description description) {72 description.appendText("state with ").appendValue(expectedSize)73 .appendText(" stack frames");74 }75 @Override76 protected boolean matchesSafely(final JState item,77 final Description mismatchDescription) {78 final int actualSize = item.stack().size();79 mismatchDescription.appendText("state with ")80 .appendValue(actualSize).appendText(" stack frames");81 return equalTo(expectedSize).matches(actualSize);82 }83 };84 }85 public static Matcher<? super JState> normalTerminiationWithResult(final Object result) {86 return both(normalTerminiation()).and(operandEqual(result));87 }88 public static Matcher<? super JState> normalTerminiationWithResultMatching(final Matcher<Object> matcher) {89 return both(normalTerminiation()).and(operandMatching(matcher));90 }...
Source:ResponseMatchers.java
...38 */39 public static <T> Matcher<Response<T>> hasNoHeaders() {40 return new TypeSafeMatcher<Response<T>>() {41 @Override42 protected boolean matchesSafely(Response<T> item) {43 return !item.headerEntries().iterator().hasNext();44 }45 @Override46 public void describeTo(Description description) {47 description.appendText("a response without headers");48 }49 @Override50 protected void describeMismatchSafely(Response<T> item, Description mismatchDescription) {51 mismatchDescription.appendText("it contained headers ").appendValue(item.headerEntries());52 }53 };54 }55 /**56 * Builds a matcher for {@link Response}s with matching header.57 * @param header The header to match.58 * @param valueMatcher {@link Matcher} for the corresponding value.59 * @return A matcher60 */61 public static <T> Matcher<Response<T>> hasHeader(String header, Matcher<String> valueMatcher) {62 return new FeatureMatcher<Response<T>, String>(valueMatcher,63 String.format("a response with header \"%s\" matching", header),64 "value") {65 @Override66 protected String featureValueOf(Response<T> actual) {67 return actual.header(header).orElse(null);68 }69 };70 }71 /**72 * Builds a matcher for {@link Response}s without specific header.73 * @param header Name of the unwanted header.74 * @return A matcher75 */76 public static <T> Matcher<Response<T>> doesNotHaveHeader(String header) {77 return new TypeSafeMatcher<Response<T>>() {78 @Override79 protected boolean matchesSafely(Response<T> item) {80 return !item.header(header).isPresent();81 }82 @Override83 public void describeTo(Description description) {84 description.appendText("a response without the header ").appendValue(header);85 }86 @Override87 protected void describeMismatchSafely(Response<T> item, Description mismatchDescription) {88 mismatchDescription.appendText("it contained the header ");89 mismatchDescription.appendValueList("{", ":", "}", header, item.header(header));90 }91 };92 }93 /**94 * Builds a matcher for {@link Response}s with no payload.95 * @return A matcher96 */97 public static <T> Matcher<Response<T>> hasNoPayload() {98 return new TypeSafeMatcher<Response<T>>() {99 @Override100 protected boolean matchesSafely(Response<T> item) {101 return !item.payload().isPresent();102 }103 @Override104 public void describeTo(Description description) {105 description.appendText("a response without payload");106 }107 @Override108 protected void describeMismatchSafely(Response<T> item, Description mismatchDescription) {109 mismatchDescription.appendText("it contained the payload: ").appendValue(item.payload().get());110 }111 };112 }113 /**114 * Builds a matcher for {@link Response}s with matching payload.115 * @param payloadMatcher {@link Matcher} for the payload.116 * @return A matcher117 */118 public static <T> Matcher<Response<? super T>> hasPayload(Matcher<? super T> payloadMatcher) {119 return new TypeSafeMatcher<Response<? super T>>() {120 @Override121 protected boolean matchesSafely(Response<? super T> item) {122 return item.payload()123 .map(payloadMatcher::matches)124 .orElse(false);125 }126 @Override127 public void describeTo(Description description) {128 description.appendText("a response with payload matching ");129 description.appendDescriptionOf(payloadMatcher);130 }131 @Override132 protected void describeMismatchSafely(Response<? super T> item, Description mismatchDescription) {133 final Optional<? super T> payload = item.payload();134 if (!payload.isPresent()) {135 mismatchDescription.appendText("there is no payload");...
Source:HttpServletRequestMatcherBuilder.java
...11 }12 public T withHeaderName (final Matcher<? super String> valueMatcher) {13 return with(new TypeSafeMatcher<HttpServletRequest>() {14 @Override15 protected boolean matchesSafely(HttpServletRequest request) {16 while (request.getHeaderNames().hasMoreElements()) {17 String headerName = request.getHeaderNames().nextElement();18 if (valueMatcher.matches(headerName))19 return true;20 }21 return false;22 }23 @Override24 public void describeTo(Description description) {25 description.appendText("Contains header name ").appendDescriptionOf(valueMatcher);26 }27 });28 }29 public T withHeader (final String name, Matcher<? super String> valueMatcher) {30 String description = String.format("Header '%s'", name);31 return with(new FeatureMatcher<HttpServletRequest, String>(valueMatcher, description, description) {32 @Override33 protected String featureValueOf(HttpServletRequest request) {34 return request.getHeader(name);35 }36 });37 }38 public T withUri (Matcher<? super String> valueMatcher) {39 String description = "Request URI";40 return with(new FeatureMatcher<HttpServletRequest, String>(valueMatcher, description, description) {41 @Override42 protected String featureValueOf(HttpServletRequest request) {43 return request.getRequestURI();44 }45 });46 }47 public T withMethod (Matcher<? super String> valueMatcher) {48 String description = "HTTP Method";49 return with(new FeatureMatcher<HttpServletRequest, String>(valueMatcher, description, description) {50 @Override51 protected String featureValueOf(HttpServletRequest request) {52 return request.getMethod();53 }54 });55 }56 public T withContentType (Matcher<? super String> valueMatcher) {57 String description = "HTTP Content-Type";58 return with(new FeatureMatcher<HttpServletRequest, String>(valueMatcher, description, description) {59 @Override60 protected String featureValueOf(HttpServletRequest request) {61 return request.getContentType();62 }63 });64 }65 public T withParameter (final String name, Matcher<? super String> matcher) {66 String description = String.format("Parameter '%s'", name);67 return with(new FeatureMatcher<HttpServletRequest, String>(matcher, description, description) {68 @Override69 protected String featureValueOf(HttpServletRequest request) {70 return request.getParameter(name);71 }72 });73 }74 public T withParameterName (final Matcher<? super String> valueMatcher) {75 return with(new TypeSafeMatcher<HttpServletRequest>() {76 @Override77 protected boolean matchesSafely(HttpServletRequest request) {78 while (request.getParameterNames().hasMoreElements()) {79 String parameterName = request.getHeaderNames().nextElement();80 if (valueMatcher.matches(parameterName))81 return true;82 }83 return false;84 }85 @Override86 public void describeTo(Description description) {87 description.appendText("Contains parameter name ").appendDescriptionOf(valueMatcher);88 }89 });90 }91}...
Source:JsonObjectMatchers.java
...35 }36 public static Matcher<JsonObject> hasProperty(String property) {37 return new TypeSafeDiagnosingMatcher<JsonObject>() {38 @Override39 protected boolean matchesSafely(JsonObject item, Description mismatchDescription) {40 boolean matches = item.containsKey(property);41 if (!matches) {42 mismatchDescription.appendText(43 "property " + "'" + property + "'" + " was not present. The following keys are present: " + quoteEntries(item.fieldNames()));44 }45 return matches;46 }47 @Override48 public void describeTo(Description description) {49 description.appendText("a JsonObject with a property " + "'" + property + "'");50 }51 };52 }53 public static Matcher<JsonObject> hasProperties(String aProperty, String anotherProperty, String... moreProprties) {54 return new TypeSafeDiagnosingMatcher<JsonObject>() {55 @Override56 protected boolean matchesSafely(JsonObject item, Description mismatchDescription) {57 Set<String> required = required();58 HashSet<String> missing = newHashSet(required);59 missing.removeAll(item.fieldNames());60 boolean matches = missing.isEmpty();61 if (!matches) {62 mismatchDescription.appendText(63 "Expected properties " + missing + " were not present. The following properties are present: "64 + quoteEntries(item.fieldNames()));65 }66 return matches;67 }68 @Override69 public void describeTo(Description description) {70 description.appendText("a JsonObject with properties " + required());...
Source:SuccessOrFailureMatchers.java
...23public enum SuccessOrFailureMatchers {24 ;25 public static final class Successful extends TypeSafeDiagnosingMatcher<SuccessOrFailure> {26 @Override27 protected boolean matchesSafely(SuccessOrFailure item, Description mismatchDescription) {28 if (item.failed()) {29 mismatchDescription.appendValue(item);30 }31 return item.succeeded();32 }33 @Override34 public void describeTo(Description description) {35 description.appendText("is successful");36 }37 }38 public static Matcher<SuccessOrFailure> successful() {39 return new Successful();40 }41 public static final class Failure extends FeatureMatcher<SuccessOrFailure, String> {42 public Failure(Matcher<? super String> subMatcher) {43 super(subMatcher, "failure message of", "failure message");44 }45 @Override46 protected String featureValueOf(SuccessOrFailure actual) {47 return actual.failureMessage();48 }49 @Override50 protected boolean matchesSafely(SuccessOrFailure actual, Description mismatch) {51 if (actual.succeeded()) {52 mismatch.appendValue(actual);53 return false;54 }55 return super.matchesSafely(actual, mismatch);56 }57 }58 public static Matcher<SuccessOrFailure> failure() {59 return new Failure(anything());60 }61 public static Matcher<SuccessOrFailure> failureWithMessage(Matcher<String> messageMatcher) {62 return new Failure(messageMatcher);63 }64 public static Matcher<SuccessOrFailure> failureWithMessage(String message) {65 return new Failure(equalTo(message));66 }67}...
Source:StatusMatcher.java
...28 description.appendText(Status.OK_STATUS.toString());29 }30 31 @Override32 protected boolean matchesSafely(IStatus item) {33 return item.isOK();34 }35 };36 }3738 public static FeatureMatcher<IStatus, Integer> severity(Matcher<? super Integer> matcher){39 return new FeatureMatcher<IStatus, Integer>(matcher, "validation result severity", "severity") { //$NON-NLS-1$ //$NON-NLS-2$40 @Override41 protected Integer featureValueOf(IStatus actual) {42 return actual.getSeverity();43 }44 };45 }46
...
Source:ParseResultMatchers.java
...5public class ParseResultMatchers {6 public static Matcher<ParseResult<?, ?>> wasSuccessful() {7 return new CustomTypeSafeMatcher<ParseResult<?, ?>>("parse result was successful") {8 @Override9 protected boolean matchesSafely(final ParseResult<?, ?> item) {10 return item.isSuccessful();11 }12 };13 }14 public static Matcher<ParseResult<?, ?>> hasNoMoreInput() {15 return new CustomTypeSafeMatcher<ParseResult<?, ?>>("parse result has no more input") {16 @Override17 protected boolean matchesSafely(final ParseResult<?, ?> item) {18 return item.getNext().isAtEnd();19 }20 };21 }22 public static <T> Matcher<ParseResult<?, T>> hasResult(final Matcher<T> resultMatcher) {23 return new FeatureMatcher<ParseResult<?, T>, T>(resultMatcher, "parse result", "parse result") {24 @Override25 protected T featureValueOf(final ParseResult<?, T> actual) {26 return actual.get();27 }28 };29 }30}...
matchesSafely
Using AI Code Generation
1package org.hamcrest;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.junit.runners.JUnit4;5import static org.hamcrest.CoreMatchers.equalTo;6@RunWith(JUnit4.class)7public class FeatureMatcherTest {8 public void testFeatureMatcher() {9 Matcher<String> matcher = new FeatureMatcher<String, String>(equalTo("Hello"), "a string starting with", "starts with") {10 protected String featureValueOf(String actual) {11 return actual.substring(0, 5);12 }13 };14 System.out.println("matcher.matches(\"Hello World\") = " + matcher.matches("Hello World"));15 }16}17matcher.matches("Hello World") = true
matchesSafely
Using AI Code Generation
1public class FeatureMatcherTest {2 public void test() {3 String str = "Hello World";4 assertThat(str, startsWith("Hello"));5 }6 private static Matcher<String> startsWith(final String prefix) {7 return new FeatureMatcher<String, String>(equalTo(prefix), "a string starting with", "starting with") {8 protected String featureValueOf(String actual) {9 return actual.substring(0, prefix.length());10 }11 };12 }13}
matchesSafely
Using AI Code Generation
1import org.hamcrest.FeatureMatcher2import org.hamcrest.Matcher3import org.hamcrest.Matchers4class Person {5 Person(String name, int age, String address) {6 }7 String getName() {8 }9 int getAge() {10 }11 String getAddress() {12 }13}14def person = new Person("John", 20, "USA")15def nameMatcher = new FeatureMatcher<Person, String>(Matchers.equalTo("John"), "name", "name") {16 protected String featureValueOf(Person actual) {17 return actual.getName()18 }19}20def ageMatcher = new FeatureMatcher<Person, Integer>(Matchers.equalTo(20), "age", "age") {21 protected Integer featureValueOf(Person actual) {22 return actual.getAge()23 }24}25def addressMatcher = new FeatureMatcher<Person, String>(Matchers.equalTo("USA"), "address", "address") {26 protected String featureValueOf(Person actual) {27 return actual.getAddress()28 }29}30assertThat(person, allOf(nameMatcher, ageMatcher, addressMatcher))31person == allOf(nameMatcher, ageMatcher, addressMatcher)
matchesSafely
Using AI Code Generation
1FeatureMatcher<String, String> containsStringMatcher = new FeatureMatcher<String, String>(null, "contains string", "string") {2 protected boolean matchesSafely(String item) {3 return item.contains(featureValueOf(this));4 }5 };6Matcher<String> containsString = containsStringMatcher;7Matcher<String> containsWorld = containsString("world");8String string = "hello world";9assertThat(string, containsWorld);
matchesSafely
Using AI Code Generation
1import org.hamcrest.FeatureMatcher2import org.hamcrest.Matcher3import org.hamcrest.Matchers4class IsPersonWithAge(val age: Int) : FeatureMatcher<Person, Int>(Matchers.equalTo(age), "Person with age", "age") {5 override fun featureValueOf(actual: Person): Int {6 }7}8fun withAge(age: Int): Matcher<Person> {9 return IsPersonWithAge(age)10}11class Person(val name: String, val age: Int)12fun main(args: Array<String>) {13 val person = Person("John", 30)14 assertThat(person, withAge(30))15}16org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)17org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)18IsPersonWithAgeKt.main(IsPersonWithAge.kt:20)19import com.nhaarman.mockitokotlin2.mock20import org.hamcrest.MatcherAssert.assertThat21import org.hamcrest.Matchers22import org.junit.Test23class IsPersonWithAgeMockitoTest {24 fun matchesSafely() {25 val person = mock<Person> {26 on { age } doReturn 3027 }28 assertThat(person, withAge(30))29 }30}31org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)32org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)33IsPersonWithAgeMockitoTest.matchesSafely(IsPersonWithAgeMockitoTest.kt:14)34import com.natpryce.hamkrest.assertion.assertThat35import com.natpryce.hamkrest.equalTo36import org.junit.Test37class IsPersonWithAgeHamcrestTest {38 fun matchesSafely() {39 val person = Person("John", 30)40 assertThat(person, withAge(30))41 }42}43org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
matchesSafely
Using AI Code Generation
1import org.hamcrest.FeatureMatcher2import org.hamcrest.Matcher3import org.hamcrest.Matchers4import org.openqa.selenium.WebElement5class CustomMatcher extends FeatureMatcher<WebElement, String> {6 CustomMatcher(Matcher<? super String> subMatcher) {7 super(subMatcher, "a WebElement with the value:", "value")8 }9 String featureValueOf(WebElement actual) {10 return actual.getAttribute("value")11 }12}13WebElement element = driver.findElement(By.id("elementId"))14assertThat(element, new CustomMatcher(Matchers.equalTo("expectedValue")))15WebElement element = driver.findElement(By.id("elementId"))16assertThat(element, new CustomMatcher(Matchers.containsString("expectedValue")))17WebElement element = driver.findElement(By.id("elementId"))18assertThat(element, new CustomMatcher(Matchers.startsWith("expectedValue")))19WebElement element = driver.findElement(By.id("elementId"))20assertThat(element, new CustomMatcher(Matchers.endsWith("expectedValue")))21WebElement element = driver.findElement(By.id("elementId"))22assertThat(element, new CustomMatcher(Matchers.not(Matchers.equalTo("expectedValue"))))23WebElement element = driver.findElement(By.id("elementId"))24assertThat(element, new CustomMatcher(Matchers.not(Matchers.containsString("expectedValue"))))
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!