How to use FeatureMatcher class of org.hamcrest package

Best junit code snippet using org.hamcrest.FeatureMatcher

Source:NestedFieldProjectionTest.java Github

copy

Full Screen

...21import com.alibaba.druid.sql.parser.Token;22import java.util.Arrays;23import java.util.List;24import java.util.function.Function;25import org.hamcrest.FeatureMatcher;26import org.hamcrest.Matcher;27import org.hamcrest.Matchers;28import org.junit.Test;29import org.mockito.Mockito;30import org.opensearch.action.search.SearchAction;31import org.opensearch.action.search.SearchRequest;32import org.opensearch.action.search.SearchRequestBuilder;33import org.opensearch.client.Client;34import org.opensearch.index.query.BoolQueryBuilder;35import org.opensearch.index.query.NestedQueryBuilder;36import org.opensearch.index.query.QueryBuilder;37import org.opensearch.search.builder.SearchSourceBuilder;38import org.opensearch.search.fetch.subphase.FetchSourceContext;39import org.opensearch.sql.legacy.domain.Select;40import org.opensearch.sql.legacy.exception.SqlParseException;41import org.opensearch.sql.legacy.parser.ElasticSqlExprParser;42import org.opensearch.sql.legacy.parser.SqlParser;43import org.opensearch.sql.legacy.query.DefaultQueryAction;44import org.opensearch.sql.legacy.query.maker.QueryMaker;45import org.opensearch.sql.legacy.rewriter.nestedfield.NestedFieldProjection;46import org.opensearch.sql.legacy.rewriter.nestedfield.NestedFieldRewriter;47import org.opensearch.sql.legacy.util.HasFieldWithValue;48public class NestedFieldProjectionTest {49 @Test50 public void regression() {51 assertThat(query("SELECT region FROM team"), is(anything()));52 assertThat(query("SELECT region FROM team WHERE nested(employees.age) = 30"), is(anything()));53 assertThat(query("SELECT * FROM team WHERE region = 'US'"), is(anything()));54 }55 @Test56 public void nestedFieldSelectAll() {57 assertThat(58 query("SELECT nested(employees.*) FROM team"),59 source(60 boolQuery(61 filter(62 boolQuery(63 must(64 nestedQuery(65 path("employees"),66 innerHits("employees.*")67 )68 )69 )70 )71 )72 )73 );74 }75 @Test76 public void nestedFieldInSelect() {77 assertThat(78 query("SELECT nested(employees.firstname) FROM team"),79 source(80 boolQuery(81 filter(82 boolQuery(83 must(84 nestedQuery(85 path("employees"),86 innerHits("employees.firstname")87 )88 )89 )90 )91 )92 )93 );94 }95 @Test96 public void regularAndNestedFieldInSelect() {97 assertThat(98 query("SELECT region, nested(employees.firstname) FROM team"),99 source(100 boolQuery(101 filter(102 boolQuery(103 must(104 nestedQuery(105 path("employees"),106 innerHits("employees.firstname")107 )108 )109 )110 )111 ),112 fetchSource("region")113 )114 );115 }116 /*117 // Should be integration test118 @Test119 public void nestedFieldInWhereSelectAll() {}120 */121 @Test122 public void nestedFieldInSelectAndWhere() {123 assertThat(124 query("SELECT nested(employees.firstname) " +125 " FROM team " +126 " WHERE nested(employees.age) = 30"),127 source(128 boolQuery(129 filter(130 boolQuery(131 must(132 nestedQuery(133 path("employees"),134 innerHits("employees.firstname")135 )136 )137 )138 )139 )140 )141 );142 }143 @Test144 public void regularAndNestedFieldInSelectAndWhere() {145 assertThat(146 query("SELECT region, nested(employees.firstname) " +147 " FROM team " +148 " WHERE nested(employees.age) = 30"),149 source(150 boolQuery(151 filter(152 boolQuery(153 must(154 nestedQuery(155 innerHits("employees.firstname")156 )157 )158 )159 )160 ),161 fetchSource("region")162 )163 );164 }165 @Test166 public void multipleSameNestedFields() {167 assertThat(168 query("SELECT nested(employees.firstname), nested(employees.lastname) " +169 " FROM team " +170 " WHERE nested(\"employees\", employees.age = 30 AND employees.firstname LIKE 'John')"),171 source(172 boolQuery(173 filter(174 boolQuery(175 must(176 nestedQuery(177 path("employees"),178 innerHits("employees.firstname", "employees.lastname")179 )180 )181 )182 )183 )184 )185 );186 }187 @Test188 public void multipleDifferentNestedFields() {189 assertThat(190 query("SELECT region, nested(employees.firstname), nested(manager.name) " +191 " FROM team " +192 " WHERE nested(employees.age) = 30 AND nested(manager.age) = 50"),193 source(194 boolQuery(195 filter(196 boolQuery(197 must(198 boolQuery(199 must(200 nestedQuery(201 path("employees"),202 innerHits("employees.firstname")203 ),204 nestedQuery(205 path("manager"),206 innerHits("manager.name")207 )208 )209 )210 )211 )212 )213 ),214 fetchSource("region")215 )216 );217 }218 @Test219 public void leftJoinWithSelectAll() {220 assertThat(221 query("SELECT * FROM team AS t LEFT JOIN t.projects AS p "),222 source(223 boolQuery(224 filter(225 boolQuery(226 should(227 boolQuery(228 mustNot(229 nestedQuery(230 path("projects")231 )232 )233 ),234 nestedQuery(235 path("projects"),236 innerHits("projects.*")237 )238 )239 )240 )241 )242 )243 );244 }245 @Test246 public void leftJoinWithSpecificFields() {247 assertThat(248 query("SELECT t.name, p.name, p.started_year FROM team AS t LEFT JOIN t.projects AS p "),249 source(250 boolQuery(251 filter(252 boolQuery(253 should(254 boolQuery(255 mustNot(256 nestedQuery(257 path("projects")258 )259 )260 ),261 nestedQuery(262 path("projects"),263 innerHits("projects.name", "projects.started_year")264 )265 )266 )267 )268 ),269 fetchSource("name")270 )271 );272 }273 private Matcher<SearchSourceBuilder> source(Matcher<QueryBuilder> queryMatcher) {274 return featureValueOf("query", queryMatcher, SearchSourceBuilder::query);275 }276 private Matcher<SearchSourceBuilder> source(Matcher<QueryBuilder> queryMatcher,277 Matcher<FetchSourceContext> fetchSourceMatcher) {278 return allOf(279 featureValueOf("query", queryMatcher, SearchSourceBuilder::query),280 featureValueOf("fetchSource", fetchSourceMatcher, SearchSourceBuilder::fetchSource)281 );282 }283 /** Asserting instanceOf and continue other chained matchers of subclass requires explicity cast */284 @SuppressWarnings("unchecked")285 private Matcher<QueryBuilder> boolQuery(Matcher<BoolQueryBuilder> matcher) {286 return (Matcher) allOf(instanceOf(BoolQueryBuilder.class), matcher);287 }288 @SafeVarargs289 @SuppressWarnings("unchecked")290 private final Matcher<QueryBuilder> nestedQuery(Matcher<NestedQueryBuilder>... matchers) {291 return (Matcher) both(is(Matchers.<NestedQueryBuilder>instanceOf(NestedQueryBuilder.class))).292 and(allOf(matchers));293 }294 @SafeVarargs295 private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> filter(Matcher<QueryBuilder>... matchers) {296 return hasClauses("filter", BoolQueryBuilder::filter, matchers);297 }298 @SafeVarargs299 private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> must(Matcher<QueryBuilder>... matchers) {300 return hasClauses("must", BoolQueryBuilder::must, matchers);301 }302 @SafeVarargs303 private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> mustNot(Matcher<QueryBuilder>... matchers) {304 return hasClauses("must_not", BoolQueryBuilder::mustNot, matchers);305 }306 @SafeVarargs307 private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> should(Matcher<QueryBuilder>... matchers) {308 return hasClauses("should", BoolQueryBuilder::should, matchers);309 }310 /** Hide contains() assertion to simplify */311 @SafeVarargs312 private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> hasClauses(String name,313 Function<BoolQueryBuilder, List<QueryBuilder>> func,314 Matcher<QueryBuilder>... matchers) {315 return new FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>>(contains(matchers), name, name) {316 @Override317 protected List<QueryBuilder> featureValueOf(BoolQueryBuilder query) {318 return func.apply(query);319 }320 };321 }322 private Matcher<NestedQueryBuilder> path(String expected) {323 return HasFieldWithValue.hasFieldWithValue("path", "path", is(equalTo(expected)));324 }325 /** Skip intermediate property along the path. Hide arrayContaining assertion to simplify. */326 private FeatureMatcher<NestedQueryBuilder, String[]> innerHits(String... expected) {327 return featureValueOf("innerHits",328 arrayContaining(expected),329 (nestedQuery -> nestedQuery.innerHit().getFetchSourceContext().includes()));330 }331 @SuppressWarnings("unchecked")332 private Matcher<FetchSourceContext> fetchSource(String... expected) {333 if (expected.length == 0) {334 return anyOf(is(nullValue()),335 featureValueOf("includes", is(nullValue()), FetchSourceContext::includes),336 featureValueOf("includes", is(emptyArray()), FetchSourceContext::includes));337 }338 return featureValueOf("includes", contains(expected), fetchSource -> Arrays.asList(fetchSource.includes()));339 }340 private <T, U> FeatureMatcher<T, U> featureValueOf(String name, Matcher<U> subMatcher, Function<T, U> getter) {341 return new FeatureMatcher<T, U>(subMatcher, name, name) {342 @Override343 protected U featureValueOf(T actual) {344 return getter.apply(actual);345 }346 };347 }348 private SearchSourceBuilder query(String sql) {349 SQLQueryExpr expr = parseSql(sql);350 if (sql.contains("nested")) {351 return translate(expr).source();352 }353 expr = rewrite(expr);354 return translate(expr).source();355 }...

Full Screen

Full Screen

Source:RestClientCallArgumentMatcher.java Github

copy

Full Screen

...9import java.util.stream.Collectors;10import org.apache.commons.lang3.tuple.Pair;11import org.hamcrest.BaseMatcher;12import org.hamcrest.Description;13import org.hamcrest.FeatureMatcher;14import org.hamcrest.Matcher;15import org.hamcrest.Matchers;16import org.hamcrest.StringDescription;17import org.mockito.ArgumentMatcher;18import org.opendevstack.provision.util.rest.RestClientCall;19import org.springframework.http.HttpMethod;20/**21 * Mockito ArgumentMatcher implementation for {@link RestClientCall} instances.22 *23 * <p>Provides a fluent api to specify features that are matched from the matcher. The internal24 * matcher implementation is done via hamcrest's {@link FeatureMatcher} class.25 *26 * <p>Beside matching, the {@link RestClientCallArgumentMatcher} also provides a very simple captor27 * implementation, wich allows to read out the captures values. Values are only captured, in case28 * the matcher matches.29 *30 * <p>See RestClientCallArgumentMatcher#bodyCaptor and RestClientCallArgumentMatcher#urlCaptor31 */32public class RestClientCallArgumentMatcher implements ArgumentMatcher<RestClientCall> {33 private final List<Pair<FeatureMatcher, Function<RestClientCall, ?>>> featureMatcherList;34 private final List<Pair<FeatureMatcher, Object>> invalidMatcherList;35 private final Map<Function<RestClientCall, Object>, ValueCaptor<?>> captorMap;36 private Description mismatchDescription;37 protected RestClientCallArgumentMatcher() {38 featureMatcherList = new ArrayList<>();39 invalidMatcherList = new ArrayList<>();40 captorMap = new HashMap<>();41 }42 public static RestClientCallArgumentMatcher matchesClientCall() {43 return new RestClientCallArgumentMatcher();44 }45 @Override46 public boolean matches(RestClientCall argument) {47 invalidMatcherList.clear();48 mismatchDescription = new StringDescription();49 for (Pair<FeatureMatcher, Function<RestClientCall, ?>> pair : featureMatcherList) {50 FeatureMatcher featureMatcher = pair.getLeft();51 featureMatcher.describeMismatch(argument, mismatchDescription);52 if (!featureMatcher.matches(argument)) {53 Function<RestClientCall, ?> valueExtractor = pair.getRight();54 Object apply = argument == null ? null : valueExtractor.apply(argument);55 invalidMatcherList.add(Pair.of(featureMatcher, apply));56 }57 }58 boolean isValid = invalidMatcherList.size() == 0;59 if (isValid) {60 captureArgumentValues(argument);61 }62 return isValid;63 }64 /**65 * For every configured captor (defined in RestClientCallArgumentMatcher#captorMap), the value is66 * read out from the given argument and stored inside the valueCaptor67 *68 * @param argument the argument where the values should be captured from69 */70 private void captureArgumentValues(RestClientCall argument) {71 for (Entry<Function<RestClientCall, Object>, ValueCaptor<?>> entry : captorMap.entrySet()) {72 Function<RestClientCall, Object> function = entry.getKey();73 ValueCaptor<Object> valueHolder = (ValueCaptor<Object>) entry.getValue();74 Object value = function.apply(argument);75 valueHolder.addValue(value);76 }77 }78 public String toString() {79 if (invalidMatcherList.isEmpty()) {80 String validMatchers =81 featureMatcherList.stream()82 .map(Pair::getLeft)83 .map(BaseMatcher::toString)84 .collect(Collectors.joining(","));85 return "All matchers suceeded: " + validMatchers;86 }87 Description description = new StringDescription();88 // result.append("A ClientCall with the following properties:");89 for (Pair<FeatureMatcher, Object> pair : invalidMatcherList) {90 FeatureMatcher invalidMatcher = pair.getLeft();91 description.appendText("Expecting '");92 invalidMatcher.describeTo(description);93 description.appendText("', but got values:").appendValue(pair.getRight());94 }95 return description.toString();96 }97 public RestClientCallArgumentMatcher url(Matcher<String> matcher) {98 addMatcher(matcher, "url", RestClientCall::getUrl);99 return this;100 }101 public RestClientCallArgumentMatcher url(String value) {102 return url(equalTo(value));103 }104 public RestClientCallArgumentMatcher urlCaptor(ValueCaptor<String> captor) {105 captorMap.put(RestClientCall::getUrl, captor);106 return this;107 }108 public RestClientCallArgumentMatcher bodyMatches(Matcher<Object> matcher) {109 addMatcher(matcher, "body", RestClientCall::getBody);110 return this;111 }112 public RestClientCallArgumentMatcher bodyEqualTo(Object value) {113 return bodyMatches(equalTo(value));114 }115 public <T> RestClientCallArgumentMatcher bodyCaptor(ValueCaptor<T> captor) {116 captorMap.put(RestClientCall::getBody, captor);117 return this;118 }119 public RestClientCallArgumentMatcher method(HttpMethod method) {120 addMatcher(equalTo(method), "method", RestClientCall::getMethod);121 return this;122 }123 public RestClientCallArgumentMatcher queryParam(String param, String value) {124 addMatcher(Matchers.hasEntry(param, value), "queryParams", RestClientCall::getQueryParams);125 return this;126 }127 public RestClientCallArgumentMatcher returnType(Class value) {128 return returnType(equalTo(value));129 }130 public RestClientCallArgumentMatcher returnType(Matcher<Object> matcher) {131 addMatcher(matcher, "returnType", RestClientCall::getReturnType);132 return this;133 }134 private <T> void addMatcher(135 Matcher<T> matcher, String featureName, Function<RestClientCall, T> valueExtractor) {136 FeatureMatcher<RestClientCall, T> featureMatcher =137 new FeatureMatcher<RestClientCall, T>(matcher, featureName, featureName) {138 public T featureValueOf(RestClientCall actual) {139 return valueExtractor.apply(actual);140 }141 };142 addMatcher(featureMatcher, valueExtractor);143 }144 protected <T> void addMatcher(145 FeatureMatcher featureMatcher, Function<RestClientCall, T> valueExtractor) {146 featureMatcherList.add(Pair.of(featureMatcher, valueExtractor));147 }148}...

Full Screen

Full Screen

Source:SdkMatchers.java Github

copy

Full Screen

1package org.openmrs.maven.plugins;2import org.hamcrest.FeatureMatcher;3import org.hamcrest.Matcher;4import org.openmrs.maven.plugins.model.OwaId;5import org.openmrs.maven.plugins.model.DistroProperties;6import org.openmrs.maven.plugins.model.Server;7import java.io.File;8import java.util.List;9import static org.hamcrest.CoreMatchers.containsString;10import static org.hamcrest.CoreMatchers.equalTo;11import static org.hamcrest.CoreMatchers.hasItem;12import static org.hamcrest.CoreMatchers.not;13import static org.hamcrest.CoreMatchers.startsWith;14public class SdkMatchers {15 public static Matcher<Server> serverHasVersion(final String version) {16 return new FeatureMatcher<Server, String>(equalTo(version), "server version", "server version") {17 @Override18 protected String featureValueOf(final Server actual) {19 return actual.getVersion();20 }21 };22 }23 public static Matcher<Server> serverHasName(final String name) {24 return new FeatureMatcher<Server, String>(equalTo(name), "distribution name", "distribution name") {25 @Override26 protected String featureValueOf(final Server actual) {27 return actual.getName();28 }29 };30 }31 public static Matcher<Server> hasUserOwa(final OwaId owa) {32 return new FeatureMatcher<Server, List<OwaId>>(hasItem(owa), "user owas", "server user owas") {33 @Override34 protected List<OwaId> featureValueOf(Server actual) {35 return actual.getUserOWAs();36 }37 };38 }39 public static Matcher<File> hasNameStartingWith(final String namePrefix) {40 return new FeatureMatcher<File, String>(startsWith(namePrefix), "file with name", "file with name") {41 @Override42 protected String featureValueOf(final File actual) {43 return actual.getName();44 }45 };46 }47 public static Matcher<Server> hasPropertyEqualTo(final String propertyName, final String propertyValue) {48 return new FeatureMatcher<Server, String>(equalTo(propertyValue), "property value", "property value") {49 @Override50 protected String featureValueOf(final Server actual) {51 return actual.getCustomProperties().get(propertyName);52 }53 };54 }55 public static Matcher<Server> hasPropertyThatContains(final String propertyName, final String propertyValue) {56 return new FeatureMatcher<Server, String>(containsString(propertyValue), "property value", "property value") {57 @Override58 protected String featureValueOf(final Server actual) {59 return actual.getServerProperty(propertyName).get(propertyName);60 }61 };62 }63 public static Matcher<Server> hasPropertyThatNotContains(final String propertyName, final String propertyValue) {64 return new FeatureMatcher<Server, String>(not(containsString(propertyValue)), "property value", "property value") {65 @Override66 protected String featureValueOf(final Server actual) {67 return actual.getServerProperty(propertyName).get(propertyName);68 }69 };70 }71 public static Matcher<Server> hasModuleVersion(final String artifactId, final String version){72 return new FeatureMatcher<Server, String>(equalTo(version), "module version", "module version") {73 @Override74 protected String featureValueOf(Server actual) {75 return actual.getParam("omod."+artifactId);76 }77 };78 }79 public static Matcher<DistroProperties> hasModuleVersionInDisstro(final String artifactId, final String version){80 return new FeatureMatcher<DistroProperties, String>(equalTo(version), "module version", "module version") {81 @Override82 protected String featureValueOf(DistroProperties actual) {83 return actual.getParam("omod."+artifactId);84 }85 };86 }87 public static Matcher<Server> hasPlatformVersion(final String version){88 return new FeatureMatcher<Server, String>(equalTo(version), "war version", "war version") {89 @Override90 protected String featureValueOf(Server actual) {91 return actual.getPlatformVersion();92 }93 };94 }95 public static Matcher<DistroProperties> hasWarVersion(final String version) {96 return new FeatureMatcher<DistroProperties, String>(equalTo(version), "war version", "war version") {97 @Override98 protected String featureValueOf(DistroProperties actual) {99 return actual.getPlatformVersion();100 }101 };102 }103 public static Matcher<Server> serverHasDebugPort(final String port) {104 return new FeatureMatcher<Server, String>(equalTo(port), "debug port", "debug port") {105 @Override106 protected String featureValueOf(final Server actual) {107 return actual.getDebugPort();108 }109 };110 }111}...

Full Screen

Full Screen

Source:FileMatchers.java Github

copy

Full Screen

...15 * limitations under the license.16 */17package org.apache.logging.log4j.hamcrest;18import java.io.File;19import org.hamcrest.FeatureMatcher;20import org.hamcrest.Matcher;21import static org.hamcrest.core.Is.is;22import static org.hamcrest.core.IsEqual.equalTo;23import static org.hamcrest.number.OrderingComparison.greaterThan;24import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;25/**26 * Hamcrest Matchers that operate on File objects.27 *28 * @since 2.129 */30public final class FileMatchers {31 /**32 * Matches if the File exists.33 *34 * @return the Matcher.35 */36 public static Matcher<File> exists() {37 return new FeatureMatcher<File, Boolean>(is(true), "file exists", "file exists") {38 @Override39 protected Boolean featureValueOf(final File actual) {40 return actual.exists();41 }42 };43 }44 /**45 * Matches a Long Matcher against the file length.46 *47 * @param matcher the Matcher to use on the File length.48 * @return the Matcher.49 */50 public static Matcher<File> hasLength(final Matcher<Long> matcher) {51 return new FeatureMatcher<File, Long>(matcher, "file with size", "file with size") {52 @Override53 protected Long featureValueOf(final File actual) {54 return actual.length();55 }56 };57 }58 /**59 * Matches a specific file length.60 *61 * @param length the file length to match62 * @param <T> the type of the length.63 * @return the Matcher.64 */65 public static <T extends Number> Matcher<File> hasLength(final T length) {66 return hasLength(equalTo(length.longValue()));67 }68 /**69 * Matches a specific file length.70 *71 * @param length the file length to match72 * @return the Matcher.73 */74 public static Matcher<File> hasLength(final long length) {75 return hasLength(equalTo(length));76 }77 /**78 * Matches a file with length equal to zero.79 *80 * @return the Matcher.81 */82 public static Matcher<File> isEmpty() {83 return hasLength(0L);84 }85 /**86 * Matches against a file's last modification time in milliseconds.87 *88 * @param matcher the Matcher to use on the File modification time.89 * @return the Matcher.90 */91 public static Matcher<File> lastModified(final Matcher<Long> matcher) {92 return new FeatureMatcher<File, Long>(matcher, "was last modified", "was last modified") {93 @Override94 protected Long featureValueOf(final File actual) {95 return actual.lastModified();96 }97 };98 }99 /**100 * Matches a time in millis before the current time.101 *102 * @return the Matcher.103 */104 public static Matcher<Long> beforeNow() {105 return lessThanOrEqualTo(System.currentTimeMillis());106 }107 /**108 * Matches the number of files in a directory.109 *110 * @param matcher the Matcher to use on the number of files.111 * @return the Matcher.112 */113 public static Matcher<File> hasNumberOfFiles(final Matcher<Integer> matcher) {114 return new FeatureMatcher<File, Integer>(matcher, "directory with number of files",115 "directory with number of files") {116 @Override117 protected Integer featureValueOf(final File actual) {118 final File[] files = actual.listFiles();119 return files == null ? 0 : files.length;120 }121 };122 }123 /**124 * Matches a directory with at least one file.125 *126 * @return the Matcher.127 */128 public static Matcher<File> hasFiles() {129 return hasNumberOfFiles(greaterThan(0));130 }131 /**132 * Matches a file name.133 *134 * @param matcher the Matcher to use on the file name.135 * @return the Matcher.136 */137 public static Matcher<File> hasName(final Matcher<String> matcher) {138 return new FeatureMatcher<File, String>(matcher, "file named", "file named") {139 @Override140 protected String featureValueOf(final File actual) {141 return actual.getName();142 }143 };144 }145 private FileMatchers() {146 }147}...

Full Screen

Full Screen

Source:StateFlowGraphMatchers.java Github

copy

Full Screen

1package com.crawljax.browser.matchers;2import com.crawljax.core.state.StateFlowGraph;3import com.crawljax.core.state.StateVertex;4import org.hamcrest.Factory;5import org.hamcrest.FeatureMatcher;6import org.hamcrest.Matcher;7import org.junit.Test;8import static org.hamcrest.Matchers.containsString;9import static org.hamcrest.core.Is.is;10import static org.hamcrest.core.IsEqual.equalTo;11import static org.hamcrest.core.IsNot.not;12import static org.junit.Assert.assertThat;13import static org.mockito.Mockito.mock;14import static org.mockito.Mockito.when;15public class StateFlowGraphMatchers {16 /**17 * @param edges The number of expected edges.18 * @return A {@link Matcher} that inspects if the number of edges.19 */20 @Factory21 public static FeatureMatcher<StateFlowGraph, Integer> hasEdges(int edges) {22 return new FeatureMatcher<StateFlowGraph, Integer>(equalTo(edges),23 "State-Flow Graph with number of edges", "number of edges") {24 @Override25 protected Integer featureValueOf(StateFlowGraph actual) {26 return actual.getAllEdges().size();27 }28 };29 }30 /**31 * @param states The number of expected states.32 * @return A {@link Matcher} that inspects if the number of states.33 */34 @Factory35 public static FeatureMatcher<StateFlowGraph, Integer> hasStates(int states) {36 return new FeatureMatcher<StateFlowGraph, Integer>(equalTo(states),37 "State-Flow Graph with number of states", "number of states") {38 @Override39 protected Integer featureValueOf(StateFlowGraph actual) {40 return actual.getAllStates().size();41 }42 };43 }44 /**45 * @param substring A {@link String} that occurs in the DOM.46 * @return A {@link Matcher} that inspects if the number of edges.47 */48 @Factory49 public static FeatureMatcher<StateVertex, String> stateWithDomSubstring(String substring) {50 return new FeatureMatcher<StateVertex, String>(containsString(substring),51 "StateVertex with in the DOM", "substring") {52 @Override53 protected String featureValueOf(StateVertex actual) {54 // System.out.println(actual.getDom());55 return actual.getDom();56 }57 };58 }59 @Test60 public void testStateWithDomSubstring() {61 StateVertex vertex = mock(StateVertex.class);62 when(vertex.getDom()).thenReturn("paap");63 assertThat(vertex, is(stateWithDomSubstring("aap")));64 assertThat(vertex, is(not(stateWithDomSubstring("bla"))));...

Full Screen

Full Screen

Source:ArtifactMatcher.java Github

copy

Full Screen

1package bhg.sucks;2import org.hamcrest.FeatureMatcher;3import org.hamcrest.Matcher;4import bhg.sucks.model.Artifact;5import bhg.sucks.model.Category;6import bhg.sucks.model.SkillContainer;7import static org.hamcrest.Matchers.allOf;8import static org.hamcrest.Matchers.contains;9import static org.hamcrest.Matchers.is;10public class ArtifactMatcher {11 public static Matcher<Artifact> name(Matcher<? super String> matcher) {12 return new FeatureMatcher<Artifact, String>(matcher, "name", "name") {13 @Override14 protected String featureValueOf(Artifact actual) {15 return actual.getName();16 }17 };18 }19 public static Matcher<Artifact> category(Matcher<? super Category> matcher) {20 return new FeatureMatcher<Artifact, Category>(matcher, "category", "category") {21 @Override22 protected Category featureValueOf(Artifact actual) {23 return actual.getCategory();24 }25 };26 }27 public static Matcher<Artifact> skills(Matcher<Iterable<? extends SkillContainer>> matcher) {28 return new FeatureMatcher<Artifact, Iterable<? extends SkillContainer>>(matcher, "skills", "skills") {29 @Override30 protected Iterable<? extends SkillContainer> featureValueOf(Artifact actual) {31 return actual.getSkills();32 }33 };34 }35 public static Matcher<Artifact> isSame(Artifact artifact) {36 return allOf(37 name(is(artifact.getName())),38 category(is(artifact.getCategory())),39 skills(contains(artifact.getSkills().toArray(new SkillContainer[0])))40 );41 }42}...

Full Screen

Full Screen

Source:n2Exercici1Test.java Github

copy

Full Screen

1/*Exercici 1. Defineix un Matcher personalitzat per a Hamcrest que proporcioni el Matcher2 * de longitud per a un String. Volem usar la classe FeatureMatcher. 3 * Amb FeatureMatcher podem ajustar un Matcher existent, decidir quin camp de l'Objecte 4 * donat baix prova ha de coincidir i proporcionar un missatge d'error agradable. 5 * El constructor de FeatureMatcher presa els següents arguments en aquest ordre:6 El matcher que volem embolicar7 Una descripció de la funció que provem8 Una descripció del possible mismatch (desajustament)9 L'únic mètode que hem de sobreescriure és featureValueOf (T actual), que retorna el 10 valor que es passarà al mètode match () / matchesSafely (). 11 Utilitzi el seu comparador personalitzat en una prova per a comprovar 12 si la cadena "Mordor" té una longitud de 8. Ajust la prova si és necessari.13 14 */15package org.itacademy.javatesting.hamcrest;16import static org.hamcrest.MatcherAssert.assertThat; 17import static org.hamcrest.Matchers.*;18import org.hamcrest.FeatureMatcher;19import org.hamcrest.Matcher;20import org.junit.Test;21public class n2Exercici1Test {22 23 public static Matcher<String> length(Matcher<? super Integer> matcher) {24 return new FeatureMatcher<String, Integer>(matcher, "Una cadena de longitud", "length") {25 @Override26 protected Integer featureValueOf(String actual) {27 return actual.length();28 }29 };30 }31 @Test32 public void fellowShipOfTheRingShouldContainer7() {33 assertThat("Mordor", length(is(8)));34 }35 36}...

Full Screen

Full Screen

Source:OrangeMatchers.java Github

copy

Full Screen

1package ru.yandex.qatools.examples.matchers;2import org.hamcrest.FeatureMatcher;3import org.hamcrest.Matcher;4import org.hamcrest.Matchers;5import ru.yandex.qatools.examples.Fruit;6import ru.yandex.qatools.examples.Shape;7import java.awt.*;8import static org.hamcrest.CoreMatchers.equalTo;9import static org.hamcrest.CoreMatchers.is;10import static org.hamcrest.Matchers.*;11/**12 * Created with IntelliJ IDEA.13 * User: lanwen14 * Date: 19.05.1315 * Time: 15:5116 */17public class OrangeMatchers {18 public static Matcher<Fruit> hasShape(final Shape shape) {19 return new FeatureMatcher<Fruit, Shape>(equalTo(shape), "fruit has shape - ", "shape -") {20 @Override21 protected Shape featureValueOf(Fruit fruit) {22 return fruit.getShape();23 }24 };25 }26 public static Matcher<Fruit> round() {27 return hasShape(Shape.ROUND);28 }29 public static Matcher<Fruit> sweet() {30 return new FeatureMatcher<Fruit, Boolean>(is(true), "fruit should be sweet", "sweet -") {31 @Override32 protected Boolean featureValueOf(Fruit fruit) {33 return fruit.isSweet();34 }35 };36 }37 public static Matcher<Fruit> hasColor(final Color color) {38 return new FeatureMatcher<Fruit, Color>(equalTo(color), "fruit have color - ", "color -") {39 @Override40 protected Color featureValueOf(Fruit fruit) {41 return fruit.getColor();42 }43 };44 }45}...

Full Screen

Full Screen

FeatureMatcher

Using AI Code Generation

copy

Full Screen

1import static org.hamcrest.MatcherAssert.assertThat;2import static org.hamcrest.Matchers.*;3import java.util.ArrayList;4import java.util.List;5import org.hamcrest.FeatureMatcher;6import org.hamcrest.Matcher;7import org.junit.Test;8public class FeatureMatcherTest {9 public void testFeatureMatcher() {10 List<BankAccount> bankAccounts = new ArrayList<BankAccount>();11 bankAccounts.add(new BankAccount(100));12 bankAccounts.add(new BankAccount(200));13 bankAccounts.add(new BankAccount(300));14 bankAccounts.add(new BankAccount(400));15 assertThat(bankAccounts, hasItem(hasProperty("balance", equalTo(300))));16 }17 private class BankAccount {18 int balance;19 public BankAccount(int balance) {20 this.balance = balance;21 }22 public int getBalance() {23 return balance;24 }25 }26}27Related posts: How to use Hamcrest’s hasProperty() method? How to use Hamcrest’s hasItem() method? How to use Hamcrest’s hasItems() method? How to use Hamcrest’s hasSize() method? How to use Hamcrest’s hasEntry() method? How to use Hamcrest’s hasKey() method? How to use Hamcrest’s hasValue() method? How to use Hamcrest’s hasToString() method? How to use Hamcrest’s hasProperty() method? How to use Hamcrest’s hasItem() method? How to use Hamcrest’s hasItems() method? How to use Hamcrest’s hasSize() method? How to use Hamcrest’s hasEntry() method? How to use Hamcrest’s hasKey() method? How to use Hamcrest’s hasValue() method? How to use Hamcrest’s hasToString() method? How to use Hamcrest’s hasProperty() method? How to use Hamcrest’s hasItem() method? How to use Hamcrest’s hasItems() method? How to use Hamcrest’s hasSize() method? How to use Hamcrest’s hasEntry() method? How to use Hamcrest’s hasKey() method? How to use Hamcrest’s has

Full Screen

Full Screen

FeatureMatcher

Using AI Code Generation

copy

Full Screen

1import static org.hamcrest.MatcherAssert.assertThat;2import static org.hamcrest.Matchers.*;3public class FeatureMatcherTest {4 public static void main(String[] args) {5 assertThat("ABC", hasLength(equalTo(3)));6 }7 private static FeatureMatcher<String, Integer> hasLength(Matcher<? super Integer> matcher) {8 return new FeatureMatcher<String, Integer>(matcher, "a string with length", "length") {9 protected Integer featureValueOf(String actual) {10 return actual.length();11 }12 };13 }14}15 at org.junit.Assert.assertEquals(Assert.java:115)16 at org.junit.Assert.assertEquals(Assert.java:144)17 at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)18 at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)19 at com.javacodegeeks.junit.FeatureMatcherTest.main(FeatureMatcherTest.java:9)

Full Screen

Full Screen

FeatureMatcher

Using AI Code Generation

copy

Full Screen

1import static org.hamcrest.CoreMatchers.instanceOf;2import org.hamcrest.BaseMatcher;3import org.hamcrest.Description;4import org.hamcrest.FeatureMatcher;5import org.hamcrest.Matcher;6import org.hamcrest.TypeSafeDiagnosingMatcher;7public class FeatureMatcherExample {8 public static void main(String[] args) {9 Matcher<Person> nameMatcher = new FeatureMatcher<Person, String>(instanceOf(String.class), "name", "no name") {10 protected String featureValueOf(Person actual) {11 return actual.getName();12 }13 };14 Matcher<Person> ageMatcher = new FeatureMatcher<Person, Integer>(instanceOf(Integer.class), "age", "no age") {15 protected Integer featureValueOf(Person actual) {16 return actual.getAge();17 }18 };19 Person person = new Person("John", 25);

Full Screen

Full Screen
copy
1class Example {2 public static void main(String[] args) {3 try {4 outerFunction();5 }6 catch (Throwable e) {7 System.err.println("Outside:");8 e.printStackTrace();9 }10 }11 static void outerFunction() throws Throwable {12 try {13 innerFunction();14 } 15 catch(Exception e) {16 System.err.println("Inside:");17 e.printStackTrace();18 throw e.fillInStackTrace();19 }20 }21 static void innerFunction() {22 throw new RuntimeException("A custom exception");23 }24} 25
Full Screen
copy
1int x;2x = 10;3
Full Screen

JUnit Tutorial:

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.

JUnit Tutorial Chapters:

Here are the detailed JUnit testing chapters to help you get started:

  • Importance of Unit testing - Learn why Unit testing is essential during the development phase to identify bugs and errors.
  • Top Java Unit testing frameworks - Here are the upcoming JUnit automation testing frameworks that you can use in 2023 to boost your unit testing.
  • What is the JUnit framework
  • Why is JUnit testing important - Learn the importance and numerous benefits of using the JUnit testing framework.
  • Features of JUnit - Learn about the numerous features of JUnit and why developers prefer it.
  • JUnit 5 vs. JUnit 4: Differences - Here is a complete comparison between JUnit 5 and JUnit 4 testing frameworks.
  • Setting up the JUnit environment - Learn how to set up your JUnit testing environment.
  • Getting started with JUnit testing - After successfully setting up your JUnit environment, this chapter will help you get started with JUnit testing in no time.
  • Parallel testing with JUnit - Parallel Testing can be used to reduce test execution time and improve test efficiency. Learn how to perform parallel testing with JUnit.
  • Annotations in JUnit - When writing automation scripts with JUnit, we can use JUnit annotations to specify the type of methods in our test code. This helps us identify those methods when we run JUnit tests using Selenium WebDriver. Learn in detail what annotations are in JUnit.
  • Assertions in JUnit - Assertions are used to validate or test that the result of an action/functionality is the same as expected. Learn in detail what assertions are and how to use them while performing JUnit testing.
  • Parameterization in JUnit - Parameterized Test enables you to run the same automated test scripts with different variables. By collecting data on each method's test parameters, you can minimize time spent on writing tests. Learn how to use parameterization in JUnit.
  • Nested Tests In JUnit 5 - A nested class is a non-static class contained within another class in a hierarchical structure. It can share the state and setup of the outer class. Learn about nested annotations in JUnit 5 with examples.
  • Best practices for JUnit testing - Learn about the best practices, such as always testing key methods and classes, integrating JUnit tests with your build, and more to get the best possible results.
  • Advanced Use Cases for JUnit testing - Take a deep dive into the advanced use cases, such as how to run JUnit tests in Jupiter, how to use JUnit 5 Mockito for Unit testing, and more for JUnit testing.

JUnit Certification:

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.

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in FeatureMatcher

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful