Best Mockito code snippet using org.mockito.ArgumentMatchers.matches
Source:ArgumentMatchers.java
...1028 reportMatcher(new Contains(substring));1029 return "";1030 }1031 /**1032 * <code>String</code> argument that matches the given regular expression.1033 * <p>1034 * See examples in javadoc for {@link ArgumentMatchers} class1035 *1036 * @param regex the regular expression.1037 * @return empty String ("").1038 */1039 public static String matches(String regex) {1040 reportMatcher(new Matches(regex));1041 return "";1042 }1043 /**1044 * <code>String</code> argument that ends with the given suffix.1045 * <p>1046 * See examples in javadoc for {@link ArgumentMatchers} class1047 *1048 * @param suffix the suffix.1049 * @return empty String ("").1050 */1051 public static String endsWith(String suffix) {1052 reportMatcher(new EndsWith(suffix));1053 return "";1054 }1055 /**1056 * <code>String</code> argument that starts with the given prefix.1057 * <p>1058 * See examples in javadoc for {@link ArgumentMatchers} class1059 *1060 * @param prefix the prefix.1061 * @return empty String ("").1062 */1063 public static String startsWith(String prefix) {1064 reportMatcher(new StartsWith(prefix));1065 return "";1066 }1067 /**1068 * Allows creating custom argument matchers.1069 *1070 * <p>1071 * This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide.1072 * <b>NullPointerException</b> auto-unboxing caveat is described below.1073 * </p>1074 *1075 * <p>1076 * It is important to understand the use cases and available options for dealing with non-trivial arguments1077 * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach1078 * for given scenario and produce highest quality test (clean and maintainable).1079 * Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples.1080 * </p>1081 *1082 * <p>1083 * <b>NullPointerException</b> auto-unboxing caveat.1084 * In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method.1085 * This way you will avoid <code>NullPointerException</code> during auto-unboxing.1086 * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem.1087 * Hopefully, the javadoc describes the problem and solution well.1088 * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker.1089 * </p>1090 *1091 * <p>1092 * See examples in javadoc for {@link ArgumentMatcher} class1093 * </p>1094 *1095 * @param matcher decides whether argument matches1096 * @return <code>null</code>.1097 */1098 public static <T> T argThat(ArgumentMatcher<T> matcher) {1099 reportMatcher(matcher);1100 return null;1101 }1102 /**1103 * Allows creating custom <code>char</code> argument matchers.1104 *1105 * Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1106 * <p>1107 * See examples in javadoc for {@link ArgumentMatchers} class1108 *1109 * @param matcher decides whether argument matches1110 * @return <code>0</code>.1111 */1112 public static char charThat(ArgumentMatcher<Character> matcher) {1113 reportMatcher(matcher);1114 return 0;1115 }1116 /**1117 * Allows creating custom <code>boolean</code> argument matchers.1118 *1119 * Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1120 * <p>1121 * See examples in javadoc for {@link ArgumentMatchers} class1122 *1123 * @param matcher decides whether argument matches1124 * @return <code>false</code>.1125 */1126 public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) {1127 reportMatcher(matcher);1128 return false;1129 }1130 /**1131 * Allows creating custom <code>byte</code> argument matchers.1132 *1133 * Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1134 * <p>1135 * See examples in javadoc for {@link ArgumentMatchers} class1136 *1137 * @param matcher decides whether argument matches1138 * @return <code>0</code>.1139 */1140 public static byte byteThat(ArgumentMatcher<Byte> matcher) {1141 reportMatcher(matcher);1142 return 0;1143 }1144 /**1145 * Allows creating custom <code>short</code> argument matchers.1146 *1147 * Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1148 * <p>1149 * See examples in javadoc for {@link ArgumentMatchers} class1150 *1151 * @param matcher decides whether argument matches1152 * @return <code>0</code>.1153 */1154 public static short shortThat(ArgumentMatcher<Short> matcher) {1155 reportMatcher(matcher);1156 return 0;1157 }1158 /**1159 * Allows creating custom <code>int</code> argument matchers.1160 *1161 * Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1162 * <p>1163 * See examples in javadoc for {@link ArgumentMatchers} class1164 *1165 * @param matcher decides whether argument matches1166 * @return <code>0</code>.1167 */1168 public static int intThat(ArgumentMatcher<Integer> matcher) {1169 reportMatcher(matcher);1170 return 0;1171 }1172 /**1173 * Allows creating custom <code>long</code> argument matchers.1174 *1175 * Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1176 * <p>1177 * See examples in javadoc for {@link ArgumentMatchers} class1178 *1179 * @param matcher decides whether argument matches1180 * @return <code>0</code>.1181 */1182 public static long longThat(ArgumentMatcher<Long> matcher) {1183 reportMatcher(matcher);1184 return 0;1185 }1186 /**1187 * Allows creating custom <code>float</code> argument matchers.1188 *1189 * Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1190 * <p>1191 * See examples in javadoc for {@link ArgumentMatchers} class1192 *1193 * @param matcher decides whether argument matches1194 * @return <code>0</code>.1195 */1196 public static float floatThat(ArgumentMatcher<Float> matcher) {1197 reportMatcher(matcher);1198 return 0;1199 }1200 /**1201 * Allows creating custom <code>double</code> argument matchers.1202 *1203 * Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.1204 * <p>1205 * See examples in javadoc for {@link ArgumentMatchers} class1206 *1207 * @param matcher decides whether argument matches1208 * @return <code>0</code>.1209 */1210 public static double doubleThat(ArgumentMatcher<Double> matcher) {1211 reportMatcher(matcher);1212 return 0;1213 }1214 private static void reportMatcher(ArgumentMatcher<?> matcher) {1215 mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher);1216 }1217}...
Source:AndroidPaymentAppFinderUnitTest.java
...35 new IntentArgumentMatcher(new Intent("org.chromium.intent.action.PAY"));36 @CalledByNative37 private AndroidPaymentAppFinderUnitTest() {}38 /**39 * Argument matcher that matches Intents using |filterEquals| method.40 */41 private static class IntentArgumentMatcher implements ArgumentMatcher<Intent> {42 private final Intent mIntent;43 public IntentArgumentMatcher(Intent intent) {44 mIntent = intent;45 }46 @Override47 public boolean matches(Intent other) {48 return mIntent.filterEquals(other);49 }50 @Override51 public String toString() {52 return mIntent.toString();53 }54 }55 private PaymentAppFactoryDelegate findApps(String[] methodNames,56 PaymentManifestDownloader downloader, PaymentManifestParser parser,57 PackageManagerDelegate packageManagerDelegate) {58 Map<String, PaymentMethodData> methodData = new HashMap<>();59 for (String methodName : methodNames) {60 PaymentMethodData data = new PaymentMethodData();61 data.supportedMethod = methodName;62 data.stringifiedData = "{\"key\":\"value\"}";63 methodData.put(methodName, data);64 }65 PaymentAppFactoryParams params = Mockito.mock(PaymentAppFactoryParams.class);66 Mockito.when(params.getWebContents()).thenReturn(Mockito.mock(WebContents.class));67 Mockito.when(params.getId()).thenReturn("id");68 Mockito.when(params.getMethodData()).thenReturn(methodData);69 Mockito.when(params.getTopLevelOrigin()).thenReturn("https://chromium.org");70 Mockito.when(params.getPaymentRequestOrigin()).thenReturn("https://chromium.org");71 Mockito.when(params.getCertificateChain()).thenReturn(null);72 Mockito.when(params.getModifiers())73 .thenReturn(new HashMap<String, PaymentDetailsModifier>());74 Mockito.when(params.getMayCrawl()).thenReturn(false);75 PaymentAppFactoryDelegate delegate = Mockito.mock(PaymentAppFactoryDelegate.class);76 Mockito.when(delegate.getParams()).thenReturn(params);77 AndroidPaymentAppFinder finder = new AndroidPaymentAppFinder(78 Mockito.mock(PaymentManifestWebDataService.class), downloader, parser,79 packageManagerDelegate, new TwaPackageManagerDelegate(), delegate,80 /*factory=*/null);81 finder.bypassIsReadyToPayServiceInTest();82 finder.findAndroidPaymentApps();83 return delegate;84 }85 private void verifyNoAppsFound(PaymentAppFactoryDelegate delegate) {86 Mockito.verify(delegate, Mockito.never())87 .onPaymentAppCreated(Mockito.any(PaymentApp.class));88 Mockito.verify(delegate, Mockito.never())89 .onPaymentAppCreationError(Mockito.any(String.class));90 Mockito.verify(delegate, Mockito.never())91 .onAutofillPaymentAppCreatorAvailable(Mockito.any(AutofillPaymentAppCreator.class));92 Mockito.verify(delegate).onCanMakePaymentCalculated(false);93 Mockito.verify(delegate).onDoneCreatingPaymentApps(/*factory=*/null);94 }95 @CalledByNativeJavaTest96 public void testNoValidPaymentMethodNames() {97 verifyNoAppsFound(findApps(new String[] {"unknown-payment-method-name",98 "http://not.secure.payment.method.name.com", "https://"},99 Mockito.mock(PaymentManifestDownloader.class),100 Mockito.mock(PaymentManifestParser.class),101 Mockito.mock(PackageManagerDelegate.class)));102 }103 @CalledByNativeJavaTest104 public void testQueryWithoutApps() {105 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);106 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(107 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))108 .thenReturn(new ArrayList<ResolveInfo>());109 verifyNoAppsFound(110 findApps(new String[] {"basic-card"}, Mockito.mock(PaymentManifestDownloader.class),111 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));112 Mockito.verify(packageManagerDelegate, Mockito.never())113 .getStringArrayResourceForApplication(114 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());115 }116 @CalledByNativeJavaTest117 public void testQueryWithoutMetaData() {118 List<ResolveInfo> activities = new ArrayList<>();119 ResolveInfo alicePay = new ResolveInfo();120 alicePay.activityInfo = new ActivityInfo();121 alicePay.activityInfo.packageName = "com.alicepay.app";122 alicePay.activityInfo.name = "com.alicepay.app.WebPaymentActivity";123 activities.add(alicePay);124 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);125 Mockito.when(packageManagerDelegate.getAppLabel(Mockito.any(ResolveInfo.class)))126 .thenReturn("A non-empty label");127 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(128 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))129 .thenReturn(activities);130 verifyNoAppsFound(131 findApps(new String[] {"basic-card"}, Mockito.mock(PaymentManifestDownloader.class),132 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));133 Mockito.verify(packageManagerDelegate, Mockito.never())134 .getStringArrayResourceForApplication(135 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());136 }137 @CalledByNativeJavaTest138 public void testQueryWithoutLabel() {139 List<ResolveInfo> activities = new ArrayList<>();140 ResolveInfo alicePay = new ResolveInfo();141 alicePay.activityInfo = new ActivityInfo();142 alicePay.activityInfo.packageName = "com.alicepay.app";143 alicePay.activityInfo.name = "com.alicepay.app.WebPaymentActivity";144 Bundle activityMetaData = new Bundle();145 activityMetaData.putString(146 AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME,147 "basic-card");148 alicePay.activityInfo.metaData = activityMetaData;149 activities.add(alicePay);150 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);151 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(152 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))153 .thenReturn(activities);154 verifyNoAppsFound(155 findApps(new String[] {"basic-card"}, Mockito.mock(PaymentManifestDownloader.class),156 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));157 Mockito.verify(packageManagerDelegate, Mockito.never())158 .getStringArrayResourceForApplication(159 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());160 }161 @CalledByNativeJavaTest162 public void testQueryUnsupportedPaymentMethod() {163 PackageManagerDelegate packageManagerDelegate = installPaymentApps(164 new String[] {"com.alicepay.app"}, new String[] {"unsupported-payment-method"});165 verifyNoAppsFound(findApps(new String[] {"unsupported-payment-method"},166 Mockito.mock(PaymentManifestDownloader.class),167 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));168 Mockito.verify(packageManagerDelegate, Mockito.never())169 .getStringArrayResourceForApplication(170 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());171 }172 private static PackageManagerDelegate installPaymentApps(173 String[] packageNames, String[] methodNames) {174 assert packageNames.length == methodNames.length;175 List<ResolveInfo> activities = new ArrayList<>();176 for (int i = 0; i < packageNames.length; i++) {177 ResolveInfo alicePay = new ResolveInfo();178 alicePay.activityInfo = new ActivityInfo();179 alicePay.activityInfo.packageName = packageNames[i];180 alicePay.activityInfo.name = packageNames[i] + ".WebPaymentActivity";181 Bundle activityMetaData = new Bundle();182 activityMetaData.putString(183 AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME,184 methodNames[i]);185 alicePay.activityInfo.metaData = activityMetaData;186 activities.add(alicePay);187 }188 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);189 Mockito.when(packageManagerDelegate.getAppLabel(Mockito.any(ResolveInfo.class)))190 .thenReturn("A non-empty label");191 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(192 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))193 .thenReturn(activities);194 return packageManagerDelegate;195 }196 @CalledByNativeJavaTest197 public void testQueryDifferentPaymentMethod() {198 PackageManagerDelegate packageManagerDelegate =199 installPaymentApps(new String[] {"com.alicepay.app"}, new String[] {"basic-card"});200 verifyNoAppsFound(findApps(new String[] {"interledger"},201 Mockito.mock(PaymentManifestDownloader.class),202 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));203 Mockito.verify(packageManagerDelegate, Mockito.never())204 .getStringArrayResourceForApplication(205 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());206 }207 @CalledByNativeJavaTest208 public void testQueryNoPaymentMethod() {209 PackageManagerDelegate packageManagerDelegate =210 installPaymentApps(new String[] {"com.alicepay.app"}, new String[] {"basic-card"});211 verifyNoAppsFound(findApps(new String[0], Mockito.mock(PaymentManifestDownloader.class),212 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate));213 Mockito.verify(packageManagerDelegate, Mockito.never())214 .getStringArrayResourceForApplication(215 ArgumentMatchers.any(ApplicationInfo.class), ArgumentMatchers.anyInt());216 }217 @CalledByNativeJavaTest218 public void testQueryBasicCardsWithTwoApps() {219 List<ResolveInfo> activities = new ArrayList<>();220 ResolveInfo alicePay = new ResolveInfo();221 alicePay.activityInfo = new ActivityInfo();222 alicePay.activityInfo.packageName = "com.alicepay.app";223 alicePay.activityInfo.name = "com.alicepay.app.WebPaymentActivity";224 alicePay.activityInfo.applicationInfo = new ApplicationInfo();225 Bundle alicePayMetaData = new Bundle();226 alicePayMetaData.putString(227 AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME,228 "basic-card");229 alicePayMetaData.putInt(AndroidPaymentAppFinder.META_DATA_NAME_OF_PAYMENT_METHOD_NAMES, 1);230 alicePay.activityInfo.metaData = alicePayMetaData;231 activities.add(alicePay);232 ResolveInfo bobPay = new ResolveInfo();233 bobPay.activityInfo = new ActivityInfo();234 bobPay.activityInfo.packageName = "com.bobpay.app";235 bobPay.activityInfo.name = "com.bobpay.app.WebPaymentActivity";236 bobPay.activityInfo.applicationInfo = new ApplicationInfo();237 Bundle bobPayMetaData = new Bundle();238 bobPayMetaData.putString(239 AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME,240 "basic-card");241 bobPayMetaData.putInt(AndroidPaymentAppFinder.META_DATA_NAME_OF_PAYMENT_METHOD_NAMES, 2);242 bobPay.activityInfo.metaData = bobPayMetaData;243 activities.add(bobPay);244 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);245 Mockito.when(packageManagerDelegate.getAppLabel(Mockito.any(ResolveInfo.class)))246 .thenReturn("A non-empty label");247 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(248 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))249 .thenReturn(activities);250 Mockito.when(packageManagerDelegate.getServicesThatCanRespondToIntent(251 ArgumentMatchers.argThat(new IntentArgumentMatcher(252 new Intent(AndroidPaymentAppFinder.ACTION_IS_READY_TO_PAY)))))253 .thenReturn(new ArrayList<ResolveInfo>());254 Mockito.when(packageManagerDelegate.getStringArrayResourceForApplication(255 ArgumentMatchers.eq(alicePay.activityInfo.applicationInfo),256 ArgumentMatchers.eq(1)))257 .thenReturn(new String[] {"https://alicepay.com"});258 Mockito.when(packageManagerDelegate.getStringArrayResourceForApplication(259 ArgumentMatchers.eq(bobPay.activityInfo.applicationInfo),260 ArgumentMatchers.eq(2)))261 .thenReturn(new String[] {"https://bobpay.com"});262 PaymentAppFactoryDelegate delegate =263 findApps(new String[] {"basic-card"}, Mockito.mock(PaymentManifestDownloader.class),264 Mockito.mock(PaymentManifestParser.class), packageManagerDelegate);265 Mockito.verify(delegate).onCanMakePaymentCalculated(true);266 Mockito.verify(delegate).onPaymentAppCreated(267 ArgumentMatchers.argThat(Matches.paymentAppIdentifier("com.alicepay.app")));268 Mockito.verify(delegate).onPaymentAppCreated(269 ArgumentMatchers.argThat(Matches.paymentAppIdentifier("com.bobpay.app")));270 Mockito.verify(delegate).onDoneCreatingPaymentApps(/*factory=*/null);271 }272 @CalledByNativeJavaTest273 public void testQueryBobPayWithOneAppThatHasIsReadyToPayService() {274 List<ResolveInfo> activities = new ArrayList<>();275 ResolveInfo bobPay = new ResolveInfo();276 bobPay.activityInfo = new ActivityInfo();277 bobPay.activityInfo.packageName = "com.bobpay.app";278 bobPay.activityInfo.name = "com.bobpay.app.WebPaymentActivity";279 bobPay.activityInfo.applicationInfo = new ApplicationInfo();280 Bundle bobPayMetaData = new Bundle();281 bobPayMetaData.putString(282 AndroidPaymentAppFinder.META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME,283 "https://bobpay.com");284 bobPayMetaData.putInt(AndroidPaymentAppFinder.META_DATA_NAME_OF_PAYMENT_METHOD_NAMES, 1);285 bobPay.activityInfo.metaData = bobPayMetaData;286 activities.add(bobPay);287 PackageManagerDelegate packageManagerDelegate = Mockito.mock(PackageManagerDelegate.class);288 Mockito.when(packageManagerDelegate.getAppLabel(Mockito.any(ResolveInfo.class)))289 .thenReturn("A non-empty label");290 Mockito.when(packageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(291 ArgumentMatchers.argThat(sPayIntentArgumentMatcher)))292 .thenReturn(activities);293 Mockito.when(packageManagerDelegate.getStringArrayResourceForApplication(294 ArgumentMatchers.eq(bobPay.activityInfo.applicationInfo),295 ArgumentMatchers.eq(1)))296 .thenReturn(new String[] {"https://bobpay.com", "basic-card"});297 List<ResolveInfo> services = new ArrayList<>();298 ResolveInfo isBobPayReadyToPay = new ResolveInfo();299 isBobPayReadyToPay.serviceInfo = new ServiceInfo();300 isBobPayReadyToPay.serviceInfo.packageName = "com.bobpay.app";301 isBobPayReadyToPay.serviceInfo.name = "com.bobpay.app.IsReadyToWebPay";302 services.add(isBobPayReadyToPay);303 Intent isReadyToPayIntent = new Intent(AndroidPaymentAppFinder.ACTION_IS_READY_TO_PAY);304 Mockito305 .when(packageManagerDelegate.getServicesThatCanRespondToIntent(306 ArgumentMatchers.argThat(new IntentArgumentMatcher(isReadyToPayIntent))))307 .thenReturn(services);308 PackageInfo bobPayPackageInfo = new PackageInfo();309 bobPayPackageInfo.versionCode = 10;310 bobPayPackageInfo.signatures = new Signature[1];311 bobPayPackageInfo.signatures[0] = PaymentManifestVerifierTest.BOB_PAY_SIGNATURE;312 Mockito.when(packageManagerDelegate.getPackageInfoWithSignatures("com.bobpay.app"))313 .thenReturn(bobPayPackageInfo);314 PaymentManifestDownloader downloader = new PaymentManifestDownloader() {315 @Override316 public void initialize(WebContents webContents) {}317 @Override318 public void downloadPaymentMethodManifest(319 Origin merchantOrigin, GURL url, ManifestDownloadCallback callback) {320 callback.onPaymentMethodManifestDownloadSuccess(url,321 PaymentManifestDownloader.createOpaqueOriginForTest(), "some content here");322 }323 @Override324 public void downloadWebAppManifest(Origin paynentMethodManifestOrigin, GURL url,325 ManifestDownloadCallback callback) {326 callback.onWebAppManifestDownloadSuccess("some content here");327 }328 @Override329 public void destroy() {}330 };331 PaymentManifestParser parser = new PaymentManifestParser() {332 @Override333 public void parsePaymentMethodManifest(334 GURL paymentMethodManifestUrl, String content, ManifestParseCallback callback) {335 callback.onPaymentMethodManifestParseSuccess(336 new GURL[] {new GURL("https://bobpay.com/app.json")}, new GURL[0]);337 }338 @Override339 public void parseWebAppManifest(String content, ManifestParseCallback callback) {340 WebAppManifestSection[] manifest = new WebAppManifestSection[1];341 int minVersion = 10;342 manifest[0] = new WebAppManifestSection("com.bobpay.app", minVersion,343 PaymentManifestVerifierTest.BOB_PAY_SIGNATURE_FINGERPRINTS);344 callback.onWebAppManifestParseSuccess(manifest);345 }346 @Override347 public void createNative(WebContents webContents) {}348 @Override349 public void destroyNative() {}350 };351 PaymentAppFactoryDelegate delegate = findApps(352 new String[] {"https://bobpay.com"}, downloader, parser, packageManagerDelegate);353 Mockito.verify(delegate).onPaymentAppCreated(354 ArgumentMatchers.argThat(Matches.paymentAppIdentifier("com.bobpay.app")));355 Mockito.verify(delegate).onDoneCreatingPaymentApps(/*factory=*/null);356 }357 private static final class Matches implements ArgumentMatcher<PaymentApp> {358 private final String mExpectedAppIdentifier;359 private Matches(String expectedAppIdentifier) {360 mExpectedAppIdentifier = expectedAppIdentifier;361 }362 /**363 * Builds a matcher based on payment app identifier.364 *365 * @param expectedAppIdentifier The expected app identifier to match.366 * @return A matcher to use in a mock expectation.367 */368 public static ArgumentMatcher<PaymentApp> paymentAppIdentifier(369 String expectedAppIdentifier) {370 return new Matches(expectedAppIdentifier);371 }372 @Override373 public boolean matches(PaymentApp app) {374 return app.getIdentifier().equals(mExpectedAppIdentifier);375 }376 }377}...
Source:TestRedirectExec.java
...105 Mockito.when(chain.proceed(106 ArgumentMatchers.same(request),107 ArgumentMatchers.any())).thenReturn(response1);108 Mockito.when(chain.proceed(109 HttpRequestMatcher.matchesRequestUri(redirect),110 ArgumentMatchers.any())).thenReturn(response2);111 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);112 redirectExec.execute(request, scope, chain);113 final ArgumentCaptor<ClassicHttpRequest> reqCaptor = ArgumentCaptor.forClass(ClassicHttpRequest.class);114 Mockito.verify(chain, Mockito.times(2)).proceed(reqCaptor.capture(), ArgumentMatchers.same(scope));115 final List<ClassicHttpRequest> allValues = reqCaptor.getAllValues();116 Assert.assertNotNull(allValues);117 Assert.assertEquals(2, allValues.size());118 Assert.assertSame(request, allValues.get(0));119 Mockito.verify(response1, Mockito.times(1)).close();120 Mockito.verify(inStream1, Mockito.times(2)).close();121 Mockito.verify(response2, Mockito.never()).close();122 Mockito.verify(inStream2, Mockito.never()).close();123 }124 @Test125 public void testMaxRedirect() throws Exception {126 final HttpRoute route = new HttpRoute(target);127 final HttpGet request = new HttpGet("/test");128 final HttpClientContext context = HttpClientContext.create();129 final RequestConfig config = RequestConfig.custom()130 .setRedirectsEnabled(true)131 .setMaxRedirects(3)132 .build();133 context.setRequestConfig(config);134 final ClassicHttpResponse response1 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY));135 final URI redirect = new URI("http://localhost:80/redirect");136 response1.setHeader(HttpHeaders.LOCATION, redirect.toASCIIString());137 Mockito.when(chain.proceed(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(response1);138 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);139 Assert.assertThrows(RedirectException.class, () ->140 redirectExec.execute(request, scope, chain));141 }142 @Test143 public void testRelativeRedirect() throws Exception {144 final HttpRoute route = new HttpRoute(target);145 final HttpGet request = new HttpGet("/test");146 final HttpClientContext context = HttpClientContext.create();147 final ClassicHttpResponse response1 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY));148 final URI redirect = new URI("/redirect");149 response1.setHeader(HttpHeaders.LOCATION, redirect.toASCIIString());150 Mockito.when(chain.proceed(151 ArgumentMatchers.same(request),152 ArgumentMatchers.any())).thenReturn(response1);153 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);154 Assert.assertThrows(HttpException.class, () ->155 redirectExec.execute(request, scope, chain));156 }157 @Test158 public void testCrossSiteRedirect() throws Exception {159 final HttpHost proxy = new HttpHost("proxy");160 final HttpRoute route = new HttpRoute(target, proxy);161 final HttpGet request = new HttpGet("/test");162 final HttpClientContext context = HttpClientContext.create();163 final AuthExchange targetAuthExchange = new AuthExchange();164 targetAuthExchange.setState(AuthExchange.State.SUCCESS);165 targetAuthExchange.select(new BasicScheme());166 final AuthExchange proxyAuthExchange = new AuthExchange();167 proxyAuthExchange.setState(AuthExchange.State.SUCCESS);168 proxyAuthExchange.select(new NTLMScheme());169 context.setAuthExchange(target, targetAuthExchange);170 context.setAuthExchange(proxy, proxyAuthExchange);171 final ClassicHttpResponse response1 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY));172 final URI redirect = new URI("http://otherhost:8888/redirect");173 response1.setHeader(HttpHeaders.LOCATION, redirect.toASCIIString());174 final ClassicHttpResponse response2 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_OK));175 final HttpHost otherHost = new HttpHost("otherhost", 8888);176 Mockito.when(chain.proceed(177 ArgumentMatchers.same(request),178 ArgumentMatchers.any())).thenReturn(response1);179 Mockito.when(chain.proceed(180 HttpRequestMatcher.matchesRequestUri(redirect),181 ArgumentMatchers.any())).thenReturn(response2);182 Mockito.when(httpRoutePlanner.determineRoute(183 ArgumentMatchers.eq(otherHost),184 ArgumentMatchers.<HttpClientContext>any())).thenReturn(new HttpRoute(otherHost));185 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);186 redirectExec.execute(request, scope, chain);187 final AuthExchange authExchange1 = context.getAuthExchange(target);188 Assert.assertNotNull(authExchange1);189 Assert.assertEquals(AuthExchange.State.UNCHALLENGED, authExchange1.getState());190 Assert.assertNull(authExchange1.getAuthScheme());191 final AuthExchange authExchange2 = context.getAuthExchange(proxy);192 Assert.assertNotNull(authExchange2);193 Assert.assertEquals(AuthExchange.State.UNCHALLENGED, authExchange2.getState());194 Assert.assertNull(authExchange2.getAuthScheme());195 }196 @Test197 public void testAllowCircularRedirects() throws Exception {198 final HttpRoute route = new HttpRoute(target);199 final HttpClientContext context = HttpClientContext.create();200 context.setRequestConfig(RequestConfig.custom()201 .setCircularRedirectsAllowed(true)202 .build());203 final URI uri = URI.create("http://localhost/");204 final HttpGet request = new HttpGet(uri);205 final URI uri1 = URI.create("http://localhost/stuff1");206 final URI uri2 = URI.create("http://localhost/stuff2");207 final ClassicHttpResponse response1 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);208 response1.addHeader("Location", uri1.toASCIIString());209 final ClassicHttpResponse response2 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);210 response2.addHeader("Location", uri2.toASCIIString());211 final ClassicHttpResponse response3 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);212 response3.addHeader("Location", uri1.toASCIIString());213 final ClassicHttpResponse response4 = new BasicClassicHttpResponse(HttpStatus.SC_OK);214 Mockito.when(chain.proceed(215 HttpRequestMatcher.matchesRequestUri(uri),216 ArgumentMatchers.any())).thenReturn(response1);217 Mockito.when(chain.proceed(218 HttpRequestMatcher.matchesRequestUri(uri1),219 ArgumentMatchers.any())).thenReturn(response2, response4);220 Mockito.when(chain.proceed(221 HttpRequestMatcher.matchesRequestUri(uri2),222 ArgumentMatchers.any())).thenReturn(response3);223 Mockito.when(httpRoutePlanner.determineRoute(224 ArgumentMatchers.eq(new HttpHost("localhost")),225 ArgumentMatchers.<HttpClientContext>any())).thenReturn(route);226 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);227 redirectExec.execute(request, scope, chain);228 final RedirectLocations uris = context.getRedirectLocations();229 Assert.assertNotNull(uris);230 Assert.assertEquals(Arrays.asList(uri1, uri2, uri1), uris.getAll());231 }232 @Test233 public void testGetLocationUriDisallowCircularRedirects() throws Exception {234 final HttpRoute route = new HttpRoute(target);235 final HttpClientContext context = HttpClientContext.create();236 context.setRequestConfig(RequestConfig.custom()237 .setCircularRedirectsAllowed(false)238 .build());239 final URI uri = URI.create("http://localhost/");240 final HttpGet request = new HttpGet(uri);241 final URI uri1 = URI.create("http://localhost/stuff1");242 final URI uri2 = URI.create("http://localhost/stuff2");243 final ClassicHttpResponse response1 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);244 response1.addHeader("Location", uri1.toASCIIString());245 final ClassicHttpResponse response2 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);246 response2.addHeader("Location", uri2.toASCIIString());247 final ClassicHttpResponse response3 = new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);248 response3.addHeader("Location", uri1.toASCIIString());249 Mockito.when(httpRoutePlanner.determineRoute(250 ArgumentMatchers.eq(new HttpHost("localhost")),251 ArgumentMatchers.<HttpClientContext>any())).thenReturn(route);252 Mockito.when(chain.proceed(253 HttpRequestMatcher.matchesRequestUri(uri),254 ArgumentMatchers.any())).thenReturn(response1);255 Mockito.when(chain.proceed(256 HttpRequestMatcher.matchesRequestUri(uri1),257 ArgumentMatchers.any())).thenReturn(response2);258 Mockito.when(chain.proceed(259 HttpRequestMatcher.matchesRequestUri(uri2),260 ArgumentMatchers.any())).thenReturn(response3);261 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);262 Assert.assertThrows(CircularRedirectException.class, () ->263 redirectExec.execute(request, scope, chain));264 }265 @Test266 public void testRedirectRuntimeException() throws Exception {267 final HttpRoute route = new HttpRoute(target);268 final HttpGet request = new HttpGet("/test");269 final HttpClientContext context = HttpClientContext.create();270 final ClassicHttpResponse response1 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY));271 final URI redirect = new URI("http://localhost:80/redirect");272 response1.setHeader(HttpHeaders.LOCATION, redirect.toASCIIString());273 Mockito.when(chain.proceed(274 ArgumentMatchers.same(request),275 ArgumentMatchers.any())).thenReturn(response1);276 Mockito.doThrow(new RuntimeException("Oppsie")).when(redirectStrategy).getLocationURI(277 ArgumentMatchers.<ClassicHttpRequest>any(),278 ArgumentMatchers.<ClassicHttpResponse>any(),279 ArgumentMatchers.<HttpClientContext>any());280 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);281 Assert.assertThrows(RuntimeException.class, () ->282 redirectExec.execute(request, scope, chain));283 Mockito.verify(response1).close();284 }285 @Test286 public void testRedirectProtocolException() throws Exception {287 final HttpRoute route = new HttpRoute(target);288 final HttpGet request = new HttpGet("/test");289 final HttpClientContext context = HttpClientContext.create();290 final ClassicHttpResponse response1 = Mockito.spy(new BasicClassicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY));291 final URI redirect = new URI("http://localhost:80/redirect");292 response1.setHeader(HttpHeaders.LOCATION, redirect.toASCIIString());293 final InputStream inStream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));294 final HttpEntity entity1 = EntityBuilder.create()295 .setStream(inStream1)296 .build();297 response1.setEntity(entity1);298 Mockito.when(chain.proceed(299 ArgumentMatchers.same(request),300 ArgumentMatchers.any())).thenReturn(response1);301 Mockito.doThrow(new ProtocolException("Oppsie")).when(redirectStrategy).getLocationURI(302 ArgumentMatchers.<ClassicHttpRequest>any(),303 ArgumentMatchers.<ClassicHttpResponse>any(),304 ArgumentMatchers.<HttpClientContext>any());305 final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context);306 Assert.assertThrows(ProtocolException.class, () ->307 redirectExec.execute(request, scope, chain));308 Mockito.verify(inStream1, Mockito.times(2)).close();309 Mockito.verify(response1).close();310 }311 private static class HttpRequestMatcher implements ArgumentMatcher<ClassicHttpRequest> {312 private final URI expectedRequestUri;313 HttpRequestMatcher(final URI requestUri) {314 super();315 this.expectedRequestUri = requestUri;316 }317 @Override318 public boolean matches(final ClassicHttpRequest argument) {319 if (argument == null) {320 return false;321 }322 try {323 final URI requestUri = argument.getUri();324 return this.expectedRequestUri.equals(requestUri);325 } catch (final URISyntaxException ex) {326 return false;327 }328 }329 static ClassicHttpRequest matchesRequestUri(final URI requestUri) {330 return ArgumentMatchers.argThat(new HttpRequestMatcher(requestUri));331 }332 }333}...
Source:OpenShiftServiceTest.java
...137 OpenShiftService openshiftService = new OpenShiftService();138 OpenShiftService spyService = Mockito.spy(openshiftService);139 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);140 doReturn(openshiftClient).when(spyService).getOpenShiftClient();141 doReturn(new StubbedPolicyBinding()).when(openshiftClient).get(ArgumentMatchers.matches(ResourceKind.POLICY_BINDING), ArgumentMatchers.anyString(), ArgumentMatchers.anyString());142 // Act143 IPolicyBinding policybinding = spyService.getPolicyBinding(policyBindingName, project);144 // Assert145 assertNotNull("policybinding can not be null.", policybinding);146 }147 @Test148 public void testUpdate() throws IOException {149 // Arrange150 String json = "{\"demoTestProject\":\"testtest\"}";151 StubbedOpenShiftProject project = new StubbedOpenShiftProject();152 OpenShiftService openshiftService = new OpenShiftService();153 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);154 OpenShiftService spyService = Mockito.spy(openshiftService);155 doReturn(openshiftClient).when(spyService).getOpenShiftClient();156 // Act157 spyService.update(json, project);158 // Assert159 verify(openshiftClient).update(ArgumentMatchers.any(Template.class));160 }161 @Test162 public void testCreateSecret() throws IOException {163 // Arrange164 String secretName = "demoTestSecret";165 Secret stubedsecret = new StubbedSecret(new ModelNode(), null);166 IProject project = new StubbedOpenShiftProject();167 OpenShiftService openshiftService = new OpenShiftService();168 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);169 OpenShiftService spyService = Mockito.spy(openshiftService);170 doReturn(openshiftClient).when(spyService).getOpenShiftClient();171 doReturn(stubedsecret).when(openshiftClient).create(ArgumentMatchers.any(StubbedSecret.class));172 StubbedResourceFactory stubedResourceFactory = Mockito.mock(StubbedResourceFactory.class);173 doReturn(stubedResourceFactory).when(openshiftClient).getResourceFactory();174 doReturn(new StubbedSecret(new ModelNode(), null)).when(stubedResourceFactory).stub(ArgumentMatchers.matches(ResourceKind.SECRET), ArgumentMatchers.matches(secretName), ArgumentMatchers.matches(project.getNamespace()));175 // Act176 Secret secret = spyService.createSecret(secretName, project, stubedsecret);177 // Assert178 assertNotNull("secret can not be null", secret);179 }180 @Test181 public void testAddSecretToServiceAccount() throws IOException {182 // Arrange183 String username = "demoTestUsername";184 OpenShiftService openshiftService = new OpenShiftService();185 StubbedSecret secret = new StubbedSecret(new ModelNode(), null);186 StubbedOpenShiftProject project = new StubbedOpenShiftProject();187 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);188 OpenShiftService spyService = Mockito.spy(openshiftService);189 doReturn(openshiftClient).when(spyService).getOpenShiftClient();190 doReturn(new StubbedServiceAccount(new ModelNode(), null, null)).when(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("ServiceAccount"), ArgumentMatchers.matches(project.getNamespace()), ArgumentMatchers.matches(username), ArgumentMatchers.isNull(), ArgumentMatchers.isNull());191 doReturn(new StubbedServiceAccount(new ModelNode(), null, null)).when(openshiftClient).update(ArgumentMatchers.any(IResource.class));192 // Act193 ServiceAccount serviceaccount = spyService.addImagePullSecretToServiceAccount(secret, username, project);194 // Assert195 assertNotNull("serviceaccount can not be null.", serviceaccount);196 }197 @Test198 public void testGetConfigMaps() throws IOException {199 // Arrange200 String namespace = "demoTestNamespace";201 OpenShiftService openshiftService = new OpenShiftService();202 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);203 OpenShiftService spyService = Mockito.spy(openshiftService);204 doReturn(openshiftClient).when(spyService).getOpenShiftClient();205 doReturn(null).when(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("configmaps"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(IResource.class));206 // Act207 Collection<IResource> configmaps = spyService.getConfigMaps(namespace);208 // Assert209 assertNull(configmaps);210 verify(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("configmaps"), ArgumentMatchers.matches("demoTestNamespace"), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull());211 }212 @Test213 public void testGetSecretsWithNotEmptyList() throws IOException {214 // Arrange215 String namespace = "demoTestNamespace";216 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);217 OpenShiftService openshiftService = new OpenShiftService();218 OpenShiftService spyService = Mockito.spy(openshiftService);219 doReturn(openshiftClient).when(spyService).getOpenShiftClient();220 doReturn(null).when(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("secrets"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(IResource.class));221 // Act222 Collection<IResource> secrets = spyService.getSecrets(namespace);223 // Assert224 assertNull(secrets);225 verify(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("secrets"), ArgumentMatchers.anyString(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull());226 }227 @Test228 public void testCreateSecretFromPath() throws IOException {229 // Arrange230 String namespace = "demoTestNamespace";231 String secretName = "demoSecret";232 String secretPath = "/";233 OpenShiftService openshiftService = new OpenShiftService();234 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);235 SecretBuilder secretBuilder = Mockito.mock(SecretBuilder.class);236 OpenShiftService spyService = Mockito.spy(openshiftService);237 doReturn(openshiftClient).when(spyService).getOpenShiftClient();238 doReturn(secretBuilder).when(spyService).getSecretBuilder(ArgumentMatchers.any(IClient.class));239 doReturn(new StubbedSecret(new ModelNode(), null)).when(secretBuilder).build(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString());240 doReturn(new StubbedSecret(new ModelNode(), null)).when(openshiftClient).create(ArgumentMatchers.any(IResource.class));241 // Act String secretPath, String secretName, String namespace242 Secret secret = spyService.createSecret(secretPath, secretName, namespace);243 // Assert244 assertNotNull("secret can not be null.", secret);245 }246 @Test247 public void testCreateDockerSecret() throws IOException {248 // Arrange249 String name = "demoTestDockerSecret";250 String secretFilePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "secrets/docker";251 OpenShiftService openshiftService = new OpenShiftService();252 OpenShiftService spyService = Mockito.spy(openshiftService);253 StubbedOpenShiftProject project = new StubbedOpenShiftProject();254 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);255 doReturn(openshiftClient).when(spyService).getOpenShiftClient();256 StubbedResourceFactory stubedResourceFactory = Mockito.mock(StubbedResourceFactory.class);257 doReturn(stubedResourceFactory).when(openshiftClient).getResourceFactory();258 doReturn(new StubbedSecret(new ModelNode(), null)).when(stubedResourceFactory).stub(ArgumentMatchers.matches(ResourceKind.SECRET), ArgumentMatchers.anyString(), ArgumentMatchers.anyString());259 // Act260 spyService.createDockerSecret(name, secretFilePath, project);261 // Assert262 verify(openshiftClient).create(ArgumentMatchers.any());263 }264 /**265 * This only tests the first client.execute call. The second call was added to fix an error returned from openshift.266 * @throws IOException267 * @throws CatapultException268 */269 @Test270 public void testAddImagePullSecretToServiceAccount() throws IOException, CatapultException {271 // Arrange272 String username = "demoTestUsername";273 StubbedSecret secret = new StubbedSecret(new ModelNode(), null);274 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);275 OpenShiftService openshiftService = new OpenShiftService();276 OpenShiftService spyService = Mockito.spy(openshiftService);277 doReturn(openshiftClient).when(spyService).getOpenShiftClient();278 doReturn(new StubbedServiceAccount(new ModelNode(), null, null)).when(openshiftClient).execute(ArgumentMatchers.matches("GET"), ArgumentMatchers.matches("ServiceAccount"), ArgumentMatchers.matches(secret.getNamespace()), ArgumentMatchers.matches(username), ArgumentMatchers.isNull(), ArgumentMatchers.isNull());279 // Act280 ServiceAccount serviceAccount = spyService.addSecretToServiceAccount(secret, username);281 // Assert282 assertNotNull("serviceAccount must be not null.", serviceAccount);283 }284 @Test285 public void testTriggerBuild() throws IOException {286 // Arrange287 String repositoryUrl = "http://repository.url/demotest";288 String commitId = "12345678";289 OpenShiftService openshiftService = new OpenShiftService();290 StubbedOpenShiftProject project = new StubbedOpenShiftProject();291 StubbedOpenShiftClient openshiftClient = Mockito.mock(StubbedOpenShiftClient.class);292 OpenShiftService spyService = Mockito.spy(openshiftService);293 doReturn(openshiftClient).when(spyService).getOpenShiftClient();294 when(openshiftClient.execute(ArgumentMatchers.matches("GET"),295 ArgumentMatchers.matches("BuildConfig"),296 ArgumentMatchers.matches(project.getName()),297 ArgumentMatchers.isNull(),298 ArgumentMatchers.isNull(),299 ArgumentMatchers.isNull())).thenReturn(new com.openshift.internal.restclient.model.List(new ModelNode(), null, null));300 // Act301 spyService.triggerBuild(repositoryUrl, commitId, project);302 // Assert303 verify(spyService).triggerBuild(repositoryUrl, commitId, project);304 }305}...
Source:MatchersMixin.java
...280 default long longThat(ArgumentMatcher<Long> matcher) {281 return ArgumentMatchers.longThat(matcher);282 }283 /**284 * Delegate call to public static java.lang.String org.mockito.ArgumentMatchers.matches(java.util.regex.Pattern)285 * {@link org.mockito.ArgumentMatchers#matches(java.util.regex.Pattern)}286 */287 default String matches(Pattern pattern) {288 return ArgumentMatchers.matches(pattern);289 }290 /**291 * Delegate call to public static java.lang.String org.mockito.ArgumentMatchers.matches(java.lang.String)292 * {@link org.mockito.ArgumentMatchers#matches(java.lang.String)}293 */294 default String matches(String regex) {295 return ArgumentMatchers.matches(regex);296 }297 /**298 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.notNull()299 * {@link org.mockito.ArgumentMatchers#notNull()}300 */301 default <T> T notNull() {302 return ArgumentMatchers.notNull();303 }304 /**305 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.nullable(java.lang.Class<T>)306 * {@link org.mockito.ArgumentMatchers#nullable(java.lang.Class)}307 */308 default <T> T nullable(Class<T> clazz) {309 return ArgumentMatchers.nullable(clazz);...
Source:MockitoMatchersTest.java
...101 }102 @Test103 public void testContainsCaseInsensitive() {104 ArgumentMatcher<String> matcher = MockitoMatchers.containsCaseInsensitive("tst");105 assertFalse(matcher.matches(null));106 assertFalse(matcher.matches(""));107 assertFalse(matcher.matches("?"));108 assertFalse(matcher.matches("t"));109 assertFalse(matcher.matches("s"));110 assertTrue(matcher.matches("teststring"));111 assertTrue(matcher.matches("tst"));112 assertTrue(matcher.matches("teststring".toUpperCase()));113 assertTrue(matcher.matches("eTstRIng"));114 assertTrue(matcher.matches("TestStr"));115 matcher = MockitoMatchers.containsCaseInsensitive("TST");116 assertFalse(matcher.matches("t"));117 assertFalse(matcher.matches("s"));118 assertTrue(matcher.matches("teststring"));119 assertTrue(matcher.matches("tst"));120 assertTrue(matcher.matches("teststring".toUpperCase()));121 assertTrue(matcher.matches("eTstRIng"));122 assertTrue(matcher.matches("TestStr"));123 }124 @Test125 public void testEqCaseInsensitive() {126 assertFalse(MockitoMatchers.eqCaseInsensitive("teststring").matches("teststr"));127 assertFalse(MockitoMatchers.eqCaseInsensitive("teststring").matches("eststring"));128 assertFalse(MockitoMatchers.eqCaseInsensitive("teststring").matches(" teststring"));129 assertTrue(MockitoMatchers.eqCaseInsensitive("teststring").matches("teststring"));130 assertTrue(MockitoMatchers.eqCaseInsensitive("teststring").matches("teststring".toUpperCase()));131 assertTrue(MockitoMatchers.eqCaseInsensitive("teststring".toUpperCase()).matches("teststring"));132 assertTrue(MockitoMatchers.eqCaseInsensitive("teststring").matches("tesTString"));133 assertTrue(MockitoMatchers.eqCaseInsensitive("tesTString").matches("teststring"));134 }135 @Test136 public void testNullValueArrayWorking() {137 ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);138 Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(15);139 Object[] arg = new Object[] { null, null };140 int actual = method.call(arg);141 assertEquals(15, actual);142 }143 @Test144 public void testNullValueArrayEq() {145 ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);146 Object[] arg = { "", 1 };147 Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(15);148 int actual = method.call(arg);149 assertEquals(15, actual);150 }151 @Test152 public void testVerifyNullValueArrayEq() {153 ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);154 Object[] arg = { "", "" };155 method.call(arg);156 verify(method).call(ArgumentMatchers.<String>any());157 verify(method).call(ArgumentMatchers.<Object>any());158 }159 @Test160 public void testObjectArrayMockitoMatchers() {161 ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);162 Object[] arg = new Object[] { "", "" };163 Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(10);164 int actual = method.call(arg);165 verify(method).call(arg);166 assertEquals(10, actual);167 arg = new Object[] { "", 1 };168 Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(12);169 actual = method.call(arg);170 verify(method).call(arg);171 assertEquals(12, actual);172 Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(15);173 arg = new Object[] { "", Long.valueOf(2), new Date() };174 actual = method.call(arg);175 verify(method).call(arg);176 assertEquals(15, actual);177 }178 @Test179 public void testObjectArray() {180 ArgumentMatcher<Object[]> allObjectArraysMatcher = MockitoMatchers.objectArray((Object[]) null);181 assertTrue("null Array", allObjectArraysMatcher.matches(null));182 assertTrue("Empty Array", allObjectArraysMatcher.matches(new Object[0]));183 assertTrue("Two Objects Array null values", allObjectArraysMatcher.matches(new Object[2]));184 assertTrue("Two Objects Array String and int values", allObjectArraysMatcher.matches(new Object[] { "1", 1 }));185 }186 static class ObjectArrayMethod {187 public int call(Object... objects) {188 return 0;189 }190 }191 public interface StringArg {192 String exec(String arg);193 }194}...
Source:FlashForgeDreamerClientTest.java
...39 "Tool Count: 2\n" +40 "ok";41 Mockito.doReturn(answer)42 .when(this.client)43 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),44 ArgumentMatchers.eq(8899),45 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_GENERAL_INFO),46 ArgumentMatchers.eq(null));47 this.client.updateGeneralInfo(this.printer);48 assertThat("Flashforge Dreamer").isEqualTo(this.printer.getMachineType());49 assertThat("error23_dreamer").isEqualTo(this.printer.getMachineName());50 assertThat("V2.15 20200917").isEqualTo(this.printer.getFirmware());51 assertThat(230.0).isEqualTo(this.printer.getMaxX());52 assertThat(150.0).isEqualTo(this.printer.getMaxY());53 assertThat(140.0).isEqualTo(this.printer.getMaxZ());54 assertThat(2).isEqualTo(this.printer.getExtruderNumber());55 }56 @Test57 void whenUpdateTemperature_thanSuccess() {58 String answer = "CMD M105 Received.\n" +59 "T0:35 /0 T1:20 /0 B:25 /0\n" +60 "ok";61 Mockito.doReturn(answer)62 .when(this.client)63 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),64 ArgumentMatchers.eq(8899),65 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_TEMPERATURE),66 ArgumentMatchers.eq(null));67 this.client.updateTemperature(this.printer);68 assertThat(35).isEqualTo(this.printer.getTemperatureExtruderLeft());69 assertThat(20).isEqualTo(this.printer.getTemperatureExtruderRight());70 assertThat(25).isEqualTo(this.printer.getTemperatureBed());71 }72 @Test73 void whenUpdatePositions_thanSuccess() {74 String answer = "CMD M114 Received.\n" +75 "X:123.001 Y:79.9912 Z:10.5 A:0 B:0\n" +76 "ok";77 Mockito.doReturn(answer)78 .when(this.client)79 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),80 ArgumentMatchers.eq(8899),81 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_POSITIONS),82 ArgumentMatchers.eq(null));83 this.client.updatePositions(this.printer);84 assertThat(this.printer.getX()).isEqualTo(123.001);85 assertThat(this.printer.getY()).isEqualTo(79.9912);86 assertThat(this.printer.getZ()).isEqualTo(10.5);87 }88 @Test89 void whenUpdatePrintingProgress_thanSuccess() {90 String answer = "CMD M27 Received.\n" +91 "SD printing byte 896065/5019767\n" +92 "ok";93 Mockito.doReturn(answer)94 .when(this.client)95 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),96 ArgumentMatchers.eq(8899),97 ArgumentMatchers.eq(FlashForgeDreamerCommands.GET_PRINTING_PROGRESS),98 ArgumentMatchers.eq(null));99 this.client.updatePrintingProgress(this.printer);100 assertThat(this.printer.getPrintingProgress()).isEqualTo(17.85);101 }102 @Test103 void whenSetColor_thanSuccess() {104 Mockito.doReturn("")105 .when(this.client)106 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),107 ArgumentMatchers.eq(8899),108 ArgumentMatchers.eq(FlashForgeDreamerCommands.SET_COLOR),109 ArgumentMatchers.eq("r255 g0 b0 F0"));110 this.client.setColor(this.printer, ColorRGB.RED);111 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),112 ArgumentMatchers.eq(8899),113 ArgumentMatchers.eq(FlashForgeDreamerCommands.SET_COLOR),114 ArgumentMatchers.eq("r255 g0 b0 F0"));115 }116 @Test117 void whenSendHello_thanSuccess() {118 Mockito.doReturn("")119 .when(this.client)120 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),121 ArgumentMatchers.eq(8899),122 ArgumentMatchers.eq(FlashForgeDreamerCommands.HELLO),123 ArgumentMatchers.eq(null));124 this.client.sendHello(this.printer);125 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),126 ArgumentMatchers.eq(8899),127 ArgumentMatchers.eq(FlashForgeDreamerCommands.HELLO),128 ArgumentMatchers.eq(null));129 }130 @Test131 void whenSendHello_thanFail() {132 assertThrows(FlashForgeDreamerClientException.class, () -> this.client.sendHello(this.printer));133 }134 @Test135 void whenSendBuy_thanSuccess() {136 Mockito.doReturn("")137 .when(this.client)138 .sendCommand(ArgumentMatchers.matches("192.168.0.3"),139 ArgumentMatchers.eq(8899),140 ArgumentMatchers.eq(FlashForgeDreamerCommands.BUY),141 ArgumentMatchers.eq(null));142 this.client.sendBuy(this.printer);143 Mockito.verify(this.client, Mockito.times(1)).sendCommand(ArgumentMatchers.matches("192.168.0.3"),144 ArgumentMatchers.eq(8899),145 ArgumentMatchers.eq(FlashForgeDreamerCommands.BUY),146 ArgumentMatchers.eq(null));147 }148}...
Source:ArgumentMatcherTest.java
...47 public void stringMatchers() {48 ArgumentMatchers.contains("string part");49 ArgumentMatchers.startsWith("string start");50 ArgumentMatchers.endsWith("string end");51 ArgumentMatchers.matches("regex");52 }53 @Test54 public void conditionMatchers() {55 ArgumentMatchers.intThat(value -> value > 2);56 ArgumentMatchers.longThat(value -> value < 100);57 ArgumentMatchers.booleanThat(value -> !value);58 }59 @Test60 public void shouldCheckIfAdult() {61 AdultChecker adultChecker = mock(AdultChecker.class);62 when(adultChecker.checkIfAdult(intThat(age -> age < 18))).thenReturn(false);63 when(adultChecker.checkIfAdult(intThat(age -> age >= 18))).thenReturn(true);64 assertThat(adultChecker.checkIfAdult(5)).isFalse();65 assertThat(adultChecker.checkIfAdult(30)).isTrue();66 }67 @Test68 public void customMatcher() {69 File file = new File("file.txt");70 File fileMatcher = ArgumentMatchers.argThat((ArgumentMatcher<File>) argument -> file.getName().endsWith(".txt"));71 ArgumentMatchers.argThat(new ArgumentMatcher<File>() {72 @Override73 public boolean matches(File argument) {74 return argument.getName().endsWith(".txt");75 }76 });77 }78 @Test79 public void nullMatchers() {80 ArgumentMatchers.notNull(); // to samo co ArgumentMatchers.isNotNull()81 ArgumentMatchers.isNotNull(); // to samo co ArgumentMatchers.notNull()82 ArgumentMatchers.isNull();83 ArgumentMatchers.nullable(Clazz.class); // null or type84 }85 @Test86 public void anyMatchers() {87 ArgumentMatchers.any();...
matches
Using AI Code Generation
1package com.automationrhapsody.junit5;2import static org.junit.jupiter.api.Assertions.assertTrue;3import static org.mockito.ArgumentMatchers.matches;4import static org.mockito.Mockito.mock;5import static org.mockito.Mockito.when;6import java.util.List;7import org.junit.jupiter.api.Test;8public class MockitoArgumentMatchersTest {9 public void testArgumentMatchers() {10 List<String> mockedList = mock(List.class);11 when(mockedList.get(matches("\\d+"))).thenReturn("element");12 assertTrue(mockedList.get(0).equals("element"));13 }14}15[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ junit5 ---16[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ junit5 ---17[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ junit5 ---18[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ junit5 ---19[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ junit5 ---
matches
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4public class MockitoDemo {5 public static void main(String[] args) {6 List mockedList = Mockito.mock(List.class);7 Mockito.when(mockedList.get(ArgumentMatchers.matches("\\d+"))).thenReturn("element");8 System.out.println(mockedList.get(1));9 System.out.println(mockedList.get(2));10 System.out.println(mockedList.get(3));11 }12}13import static org.mockito.ArgumentMatchers.matches;14import static org.mockito.Mockito.mock;15import static org.mockito.Mockito.when;16import static org.testng.Assert.assertEquals;17import java.util.ArrayList;18import java.util.List;19import org.mockito.ArgumentMatchers;20import org.mockito.Mockito;21import org.testng.annotations.Test;22public class MockitoTest {23 public void test() {24 List mockedList = mock(ArrayList.class);25 when(mockedList.get(matches("\\d+"))).thenReturn("element");26 assertEquals(mockedList.get(1), "element");27 assertEquals(mockedList.get(2), "element");28 assertEquals(mockedList.get(3), "element");29 }30}31import static org.mockito.ArgumentMatchers.matches;32import static org.mockito.Mockito.mock;33import static org.mockito.Mockito.when;34import static org.testng.Assert.assertEquals;35import java.util.ArrayList;36import java.util.List;37import org.mockito.ArgumentMatchers;38import org.mockito.Mockito;39import org.testng.annotations.Test;40public class MockitoTest {41 public void test() {42 List mockedList = mock(ArrayList.class);43 when(mockedList.get(matches("\\d+"))).thenReturn("element");44 assertEquals(mockedList.get(1), "element");45 assertEquals(mockedList.get(2), "element");46 assertEquals(mockedList.get(3), "element");47 }48}49import static org.mockito.ArgumentMatchers.matches;50import static org.mockito.Mockito.mock;51import static org.mockito.Mockito.when;52import static org.testng.Assert.assertEquals;53import java.util.ArrayList;54import java.util.List;55import org.mockito.ArgumentMatchers;56import org.mockito.Mockito;57import org.testng.annotations.Test;58public class MockitoTest {59 public void test() {60 List mockedList = mock(ArrayList
matches
Using AI Code Generation
1package com.acko.acko;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.ArgumentMatchers;5import org.mockito.Mock;6import org.mockito.junit.MockitoJUnitRunner;7import java.util.List;8import static org.mockito.Mockito.verify;9@RunWith(MockitoJUnitRunner.class)10public class Test1 {11 List<String> mockList;12 public void test1() {13 mockList.add("one");14 verify(mockList).add(ArgumentMatchers.matches("one"));15 }16}17package com.acko.acko;18import org.junit.Test;19import org.junit.runner.RunWith;20import org.mockito.ArgumentMatchers;21import org.mockito.Mock;22import org.mockito.junit.MockitoJUnitRunner;23import java.util.List;24import static org.mockito.Mockito.verify;25@RunWith(MockitoJUnitRunner.class)26public class Test2 {27 List<String> mockList;28 public void test2() {29 mockList.add("one");30 verify(mockList).add(ArgumentMatchers.matches("two"));31 }32}33package com.acko.acko;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.mockito.ArgumentMatchers;37import org.mockito.Mock;38import org.mockito.junit.MockitoJUnitRunner;39import java.util.List;40import static org.mockito.Mockito.verify;41@RunWith(MockitoJUnitRunner.class)42public class Test3 {43 List<String> mockList;44 public void test3() {45 mockList.add("one");46 verify(mockList).add(ArgumentMatchers.matches("one"));47 }48}
matches
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3public class 1 {4 public static void main(String[] args) {5 MyInterface obj = Mockito.mock(MyInterface.class);6 Mockito.when(obj.method1(ArgumentMatchers.matches("[a-z]+"))).thenReturn("method1() called");7 System.out.println(obj.method1("hello"));8 System.out.println(obj.method1("HELLO"));9 }10}11method1() called
matches
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3public class MyTest {4 public static void main(String args[]) {5 MyInterface myInterface = Mockito.mock(MyInterface.class);6 Mockito.when(myInterface.doSomething(ArgumentMatchers.matches("[a-zA-Z]+"))).thenReturn("Hello World");7 System.out.println(myInterface.doSomething("Hello"));8 }9}10import org.mockito.ArgumentMatchers;11import org.mockito.Mockito;12public class MyTest {13 public static void main(String args[]) {14 MyInterface myInterface = Mockito.mock(MyInterface.class);15 Mockito.when(myInterface.doSomething(ArgumentMatchers.startsWith("H"))).thenReturn("Hello World");16 System.out.println(myInterface.doSomething("Hello"));17 }18}19import org.mockito.ArgumentMatchers;20import org.mockito.Mockito;21public class MyTest {22 public static void main(String args[]) {23 MyInterface myInterface = Mockito.mock(MyInterface.class);24 Mockito.when(myInterface.doSomething(ArgumentMatchers.endsWith("o"))).thenReturn("Hello World");25 System.out.println(myInterface.doSomething("Hello"));26 }27}28import org.mockito.ArgumentMatchers;29import org.mockito.Mockito;30public class MyTest {31 public static void main(String args[]) {32 MyInterface myInterface = Mockito.mock(MyInterface.class);33 Mockito.when(myInterface.doSomething(ArgumentMatchers.contains("ell"))).thenReturn("Hello World");34 System.out.println(myInterface.doSomething("Hello"));35 }36}37import org.mockito.ArgumentMatchers;38import org.mockito.Mockito;39public class MyTest {40 public static void main(String args[]) {41 MyInterface myInterface = Mockito.mock(MyInterface.class);42 Mockito.when(myInterface.doSomething(ArgumentMatchers.not("Hello"))).thenReturn("Hello World");43 System.out.println(myInterface.doSomething("Hello"));44 }45}46import org.mockito.ArgumentMatchers;47import org.mockito.Mockito;48public class MyTest {
matches
Using AI Code Generation
1import static org.mockito.Matchers.*;2import static org.mockito.Mockito.*;3import org.mockito.ArgumentMatcher;4import org.mockito.ArgumentMatchers;5import org.mockito.Mockito;6public class MyClass {7 public static void main(String args[]) {8 MyClass test = mock(MyClass.class);9 when(test.add(anyInt(), anyInt())).thenReturn(5);10 when(test.add(anyInt(), eq(20))).thenReturn(10);11 System.out.println(test.add(10, 20));12 System.out.println(test.add(10, 30));13 }14 public int add(int a, int b) {15 return a + b;16 }17}18Example 2: Using ArgumentMatchers.anyString() in Mockito19import static org.mockito.Matchers.*;20import static org.mockito.Mockito.*;21import org.mockito.ArgumentMatcher;22import org.mockito.ArgumentMatchers;23import org.mockito.Mockito;24public class MyClass {25 public static void main(String args[]) {26 MyClass test = mock(MyClass.class);27 when(test.add(anyString(), anyString())).thenReturn(5);28 when(test.add(anyString(), eq("World"))).thenReturn(10);29 System.out.println(test.add("Hello", "World"));30 System.out.println(test.add("Hello", "India"));31 }32 public int add(String a, String b) {33 return a.length() + b.length();34 }35}36Example 3: Using ArgumentMatchers.any() in Mockito37import static org.mockito.Matchers.*;38import static org.mockito.Mockito.*;39import org.mockito.ArgumentMatcher;40import org.mockito.ArgumentMatchers;41import org.mockito.Mockito;42public class MyClass {43 public static void main(String args[]) {44 MyClass test = mock(MyClass.class);45 when(test.add(any(), any())).thenReturn(5);46 when(test.add(any(), eq("World"))).thenReturn(10);47 System.out.println(test.add("Hello", "World"));48 System.out.println(test.add("Hello", "India"));49 }50 public int add(String a, String b) {51 return a.length() + b.length();52 }53}54Example 4: Using ArgumentMatchers.any() in Mockito
matches
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class Test {3 public static void main(String[] args) {4 String str = "Hello World!";5 System.out.println(ArgumentMatchers.matches("Hello.*").matches(str));6 }7}
matches
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.anyString;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4public class Test {5 public static void main(String[] args) {6 MyInterface myInterface = mock(MyInterface.class);7 when(myInterface.myMethod(anyString())).thenReturn("Hello");8 System.out.println(myInterface.myMethod("World"));9 }10}11import static org.mockito.ArgumentMatchers.matches;12import static org.mockito.Mockito.mock;13import static org.mockito.Mockito.when;14public class Test {15 public static void main(String[] args) {16 MyInterface myInterface = mock(MyInterface.class);17 when(myInterface.myMethod(matches("[a-zA-Z]+"))).thenReturn("Hello");18 System.out.println(myInterface.myMethod("World"));19 }20}21import static org.mockito.ArgumentMatchers.matches;22import static org.mockito.Mockito.mock;23import static org.mockito.Mockito.when;24public class Test {25 public static void main(String[] args) {26 MyInterface myInterface = mock(MyInterface.class);27 when(myInterface.myMethod(matches("[0-9]+"))).thenReturn("Hello");28 System.out.println(myInterface.myMethod("123"));29 }30}31import static org.mockito.ArgumentMatchers.matches;32import static org.mockito.Mockito.mock;33import static org.mockito.Mockito.when;34public class Test {35 public static void main(String[] args) {36 MyInterface myInterface = mock(MyInterface.class);37 when(myInterface.myMethod(matches("[0-9]+"))).thenReturn("Hello");38 System.out.println(myInterface.myMethod("abc"));39 }40}
matches
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.Mockito.*;3public class MockitoTest{4 public static void main(String args[]){5 String str = "Hello World";6 String str1 = "Hello World";7 String str2 = "Hello World";8 String str3 = "Hello World";9 String str4 = "Hello World";10 String str5 = "Hello World";11 String str6 = "Hello World";12 String str7 = "Hello World";13 String str8 = "Hello World";14 String str9 = "Hello World";15 String str10 = "Hello World";16 String str11 = "Hello World";17 String str12 = "Hello World";18 String str13 = "Hello World";19 String str14 = "Hello World";20 String str15 = "Hello World";21 String str16 = "Hello World";22 String str17 = "Hello World";23 String str18 = "Hello World";24 String str19 = "Hello World";25 String str20 = "Hello World";26 String str21 = "Hello World";27 String str22 = "Hello World";28 String str23 = "Hello World";29 String str24 = "Hello World";30 String str25 = "Hello World";31 String str26 = "Hello World";32 String str27 = "Hello World";33 String str28 = "Hello World";34 String str29 = "Hello World";35 String str30 = "Hello World";36 String str31 = "Hello World";37 String str32 = "Hello World";38 String str33 = "Hello World";39 String str34 = "Hello World";40 String str35 = "Hello World";41 String str36 = "Hello World";42 String str37 = "Hello World";43 String str38 = "Hello World";44 String str39 = "Hello World";45 String str40 = "Hello World";46 String str41 = "Hello World";47 String str42 = "Hello World";48 String str43 = "Hello World";49 String str44 = "Hello World";50 String str45 = "Hello World";51 String str46 = "Hello World";52 String str47 = "Hello World";53 String str48 = "Hello World";54 String str49 = "Hello World";55 String str50 = "Hello World";56 String str51 = "Hello World";
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!