Best Mockito code snippet using org.mockito.ArgumentMatchers.argThat
Source:BluetoothDiscoveryServiceTest.java
...77 // this second call should not produce another result78 discoveryService.deviceDiscovered(device);79 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(80 ArgumentMatchers.same(discoveryService),81 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));82 }83 @Test84 public void ignoreOtherDuplicateTest() {85 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();86 BluetoothAdapter mockAdapter2 = new MockBluetoothAdapter();87 BluetoothAddress address = TestUtils.randomAddress();88 BluetoothDevice device1 = mockAdapter1.getDevice(address);89 BluetoothDevice device2 = mockAdapter2.getDevice(address);90 discoveryService.deviceDiscovered(device1);91 discoveryService.deviceDiscovered(device2);92 // this should not produce another result93 discoveryService.deviceDiscovered(device1);94 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2)).thingDiscovered(95 ArgumentMatchers.same(discoveryService),96 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));97 }98 @Test99 public void ignoreRssiDuplicateTest() {100 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();101 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());102 discoveryService.deviceDiscovered(device);103 // changing the rssi should not result in a new discovery104 device.setRssi(100);105 discoveryService.deviceDiscovered(device);106 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(107 ArgumentMatchers.same(discoveryService),108 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));109 }110 @Test111 public void nonDuplicateNameTest() throws InterruptedException {112 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();113 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());114 discoveryService.deviceDiscovered(device);115 // this second call should produce another result116 device.setName("sdfad");117 discoveryService.deviceDiscovered(device);118 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2)).thingDiscovered(119 ArgumentMatchers.same(discoveryService),120 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));121 }122 @Test123 public void nonDuplicateTxPowerTest() {124 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();125 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());126 discoveryService.deviceDiscovered(device);127 // this second call should produce another result128 device.setTxPower(10);129 discoveryService.deviceDiscovered(device);130 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2)).thingDiscovered(131 ArgumentMatchers.same(discoveryService),132 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));133 }134 @Test135 public void nonDuplicateManufacturerIdTest() {136 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();137 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());138 discoveryService.deviceDiscovered(device);139 // this second call should produce another result140 device.setManufacturerId(100);141 discoveryService.deviceDiscovered(device);142 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2)).thingDiscovered(143 ArgumentMatchers.same(discoveryService),144 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)));145 }146 @Test147 public void useResultFromAnotherAdapterTest() {148 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();149 BluetoothAdapter mockAdapter2 = new MockBluetoothAdapter();150 BluetoothAddress address = TestUtils.randomAddress();151 discoveryService.deviceDiscovered(mockAdapter1.getDevice(address));152 discoveryService.deviceDiscovered(mockAdapter2.getDevice(address));153 ArgumentCaptor<DiscoveryResult> resultCaptor = ArgumentCaptor.forClass(DiscoveryResult.class);154 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2))155 .thingDiscovered(ArgumentMatchers.same(discoveryService), resultCaptor.capture());156 List<DiscoveryResult> results = resultCaptor.getAllValues();157 DiscoveryResult result1 = results.get(0);158 DiscoveryResult result2 = results.get(1);159 Assert.assertNotEquals(result1.getBridgeUID(), result2.getBridgeUID());160 Assert.assertThat(result1.getBridgeUID(), anyOf(is(mockAdapter1.getUID()), is(mockAdapter2.getUID())));161 Assert.assertThat(result2.getBridgeUID(), anyOf(is(mockAdapter1.getUID()), is(mockAdapter2.getUID())));162 Assert.assertEquals(result1.getThingUID().getId(), result2.getThingUID().getId());163 Assert.assertEquals(result1.getLabel(), result2.getLabel());164 Assert.assertEquals(result1.getRepresentationProperty(), result2.getRepresentationProperty());165 }166 @Test167 public void connectionParticipantTest() {168 Mockito.doReturn(true).when(participant1).requiresConnection(ArgumentMatchers.any());169 BluetoothAddress address = TestUtils.randomAddress();170 MockBluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();171 MockBluetoothDevice mockDevice = mockAdapter1.getDevice(address);172 String deviceName = RandomStringUtils.randomAlphanumeric(10);173 mockDevice.setDeviceName(deviceName);174 BluetoothDevice device = Mockito.spy(mockDevice);175 discoveryService.deviceDiscovered(device);176 Mockito.verify(device, Mockito.timeout(TIMEOUT).times(1)).connect();177 Mockito.verify(device, Mockito.timeout(TIMEOUT).times(1)).readCharacteristic(178 ArgumentMatchers.argThat(ch -> ch.getGattCharacteristic() == GattCharacteristic.DEVICE_NAME));179 Mockito.verify(device, Mockito.timeout(TIMEOUT).times(1)).disconnect();180 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(181 ArgumentMatchers.same(discoveryService),182 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)183 && arg.getThingUID().getId().equals(deviceName)));184 }185 @Test186 public void multiDiscoverySingleConnectionTest() {187 Mockito.doReturn(true).when(participant1).requiresConnection(ArgumentMatchers.any());188 BluetoothAddress address = TestUtils.randomAddress();189 MockBluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();190 MockBluetoothAdapter mockAdapter2 = new MockBluetoothAdapter();191 MockBluetoothDevice mockDevice1 = mockAdapter1.getDevice(address);192 MockBluetoothDevice mockDevice2 = mockAdapter2.getDevice(address);193 String deviceName = RandomStringUtils.randomAlphanumeric(10);194 mockDevice1.setDeviceName(deviceName);195 mockDevice2.setDeviceName(deviceName);196 BluetoothDevice device1 = Mockito.spy(mockDevice1);197 BluetoothDevice device2 = Mockito.spy(mockDevice2);198 discoveryService.deviceDiscovered(device1);199 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(200 ArgumentMatchers.same(discoveryService),201 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)202 && mockAdapter1.getUID().equals(arg.getBridgeUID())203 && arg.getThingUID().getId().equals(deviceName)));204 Mockito.verify(device1, Mockito.times(1)).connect();205 Mockito.verify(device1, Mockito.times(1)).readCharacteristic(206 ArgumentMatchers.argThat(ch -> ch.getGattCharacteristic() == GattCharacteristic.DEVICE_NAME));207 Mockito.verify(device1, Mockito.times(1)).disconnect();208 discoveryService.deviceDiscovered(device2);209 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(210 ArgumentMatchers.same(discoveryService),211 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)212 && mockAdapter2.getUID().equals(arg.getBridgeUID())213 && arg.getThingUID().getId().equals(deviceName)));214 Mockito.verify(device2, Mockito.never()).connect();215 Mockito.verify(device2, Mockito.never()).readCharacteristic(216 ArgumentMatchers.argThat(ch -> ch.getGattCharacteristic() == GattCharacteristic.DEVICE_NAME));217 Mockito.verify(device2, Mockito.never()).disconnect();218 }219 @Test220 public void nonConnectionParticipantTest() {221 MockBluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();222 MockBluetoothDevice mockDevice = mockAdapter1.getDevice(TestUtils.randomAddress());223 String deviceName = RandomStringUtils.randomAlphanumeric(10);224 mockDevice.setDeviceName(deviceName);225 BluetoothDevice device = Mockito.spy(mockDevice);226 discoveryService.deviceDiscovered(device);227 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(228 ArgumentMatchers.same(discoveryService),229 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant1.typeUID)230 && !arg.getThingUID().getId().equals(deviceName)));231 Mockito.verify(device, Mockito.never()).connect();232 Mockito.verify(device, Mockito.never()).readCharacteristic(233 ArgumentMatchers.argThat(ch -> ch.getGattCharacteristic() == GattCharacteristic.DEVICE_NAME));234 Mockito.verify(device, Mockito.never()).disconnect();235 }236 @Test237 public void defaultResultTest() {238 Mockito.doReturn(null).when(participant1).createResult(ArgumentMatchers.any());239 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();240 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());241 discoveryService.deviceDiscovered(device);242 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))243 .thingDiscovered(ArgumentMatchers.same(discoveryService), ArgumentMatchers244 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));245 }246 @Test247 public void removeDefaultDeviceTest() {248 Mockito.doReturn(null).when(participant1).createResult(ArgumentMatchers.any());249 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();250 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());251 discoveryService.deviceDiscovered(device);252 discoveryService.deviceRemoved(device);253 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))254 .thingRemoved(ArgumentMatchers.same(discoveryService), ArgumentMatchers255 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));256 }257 @Test258 public void removeUpdatedDefaultDeviceTest() {259 Mockito.doReturn(null).when(participant1).createResult(ArgumentMatchers.any());260 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();261 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());262 discoveryService.deviceDiscovered(device);263 device.setName("somename");264 discoveryService.deviceDiscovered(device);265 discoveryService.deviceRemoved(device);266 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))267 .thingRemoved(ArgumentMatchers.same(discoveryService), ArgumentMatchers268 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));269 }270 @Test271 public void bluezConnectionTimeoutTest() {272 Mockito.doReturn(true).when(participant1).requiresConnection(ArgumentMatchers.any());273 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();274 BadConnectionDevice device = new BadConnectionDevice(mockAdapter1, TestUtils.randomAddress(), 100);275 discoveryService.deviceDiscovered(device);276 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))277 .thingDiscovered(ArgumentMatchers.same(discoveryService), ArgumentMatchers278 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));279 }280 @Test281 public void replaceOlderDiscoveryTest() {282 Mockito.doReturn(null).when(participant1).createResult(ArgumentMatchers.any());283 BluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();284 BluetoothDevice device = mockAdapter1.getDevice(TestUtils.randomAddress());285 MockDiscoveryParticipant participant2 = new MockDiscoveryParticipant() {286 @Override287 public @Nullable DiscoveryResult createResult(BluetoothDevice device) {288 Integer manufacturer = device.getManufacturerId();289 if (manufacturer != null && manufacturer.equals(10)) {290 // without a device name it should produce a random ThingUID291 return super.createResult(device);292 }293 return null;294 }295 };296 discoveryService.addBluetoothDiscoveryParticipant(participant2);297 // lets start with producing a default result298 discoveryService.deviceDiscovered(device);299 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))300 .thingDiscovered(ArgumentMatchers.same(discoveryService), ArgumentMatchers301 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));302 device.setManufacturerId(10);303 // lets start with producing a default result304 discoveryService.deviceDiscovered(device);305 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1))306 .thingRemoved(ArgumentMatchers.same(discoveryService), ArgumentMatchers307 .argThat(arg -> arg.getThingTypeUID().equals(BluetoothBindingConstants.THING_TYPE_BEACON)));308 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(1)).thingDiscovered(309 ArgumentMatchers.same(discoveryService),310 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant2.typeUID)));311 }312 @Test313 public void recursiveFutureTest() throws InterruptedException {314 /*315 * 1. deviceDiscovered(device1)316 * 2. cause discovery to pause at participant1317 * participant1 should make a field non-null for device1 upon unpause318 * 3. make the same field non-null for device2319 * 4. deviceDiscovered(device2)320 * this discovery should be waiting for first discovery to finish321 * 5. unpause participant322 * End result:323 * - participant should only have been called once324 * - thingDiscovered should have been called twice325 */326 Mockito.doReturn(null).when(participant1).createResult(ArgumentMatchers.any());327 AtomicInteger callCount = new AtomicInteger(0);328 final CountDownLatch pauseLatch = new CountDownLatch(1);329 BluetoothAddress address = TestUtils.randomAddress();330 MockBluetoothAdapter mockAdapter1 = new MockBluetoothAdapter();331 MockBluetoothAdapter mockAdapter2 = new MockBluetoothAdapter();332 MockBluetoothDevice mockDevice1 = mockAdapter1.getDevice(address);333 MockBluetoothDevice mockDevice2 = mockAdapter2.getDevice(address);334 String deviceName = RandomStringUtils.randomAlphanumeric(10);335 MockDiscoveryParticipant participant2 = new MockDiscoveryParticipant() {336 @Override337 public @Nullable DiscoveryResult createResult(BluetoothDevice device) {338 try {339 pauseLatch.await();340 } catch (InterruptedException e) {341 // do nothing342 }343 device.setName(deviceName);344 callCount.incrementAndGet();345 return super.createResult(device);346 }347 };348 discoveryService.addBluetoothDiscoveryParticipant(participant2);349 discoveryService.deviceDiscovered(mockDevice1);350 mockDevice2.setName(deviceName);351 discoveryService.deviceDiscovered(mockDevice2);352 pauseLatch.countDown();353 Mockito.verify(mockDiscoveryListener, Mockito.timeout(TIMEOUT).times(2)).thingDiscovered(354 ArgumentMatchers.same(discoveryService),355 ArgumentMatchers.argThat(arg -> arg.getThingTypeUID().equals(participant2.typeUID)));356 Assert.assertEquals(1, callCount.get());357 }358 private class MockDiscoveryParticipant implements BluetoothDiscoveryParticipant {359 private ThingTypeUID typeUID;360 public MockDiscoveryParticipant() {361 this.typeUID = new ThingTypeUID("mock", RandomStringUtils.randomAlphabetic(6));362 }363 @Override364 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {365 return Collections.singleton(typeUID);366 }367 @Override368 public @Nullable DiscoveryResult createResult(BluetoothDevice device) {369 return DiscoveryResultBuilder.create(getThingUID(device)).withLabel(RandomStringUtils.randomAlphabetic(6))...
Source:AndroidPaymentAppFinderUnitTest.java
...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(...
Source:OfflineContentAggregatorNotificationBridgeUiTest.java
1// Copyright 2017 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4package org.chromium.chrome.browser.download.items;5import static org.mockito.ArgumentMatchers.argThat;6import static org.mockito.ArgumentMatchers.eq;7import static org.mockito.Mockito.inOrder;8import static org.mockito.Mockito.never;9import static org.mockito.Mockito.times;10import static org.mockito.Mockito.verify;11import android.graphics.Bitmap;12import org.junit.Assert;13import org.junit.Rule;14import org.junit.Test;15import org.junit.runner.RunWith;16import org.mockito.ArgumentCaptor;17import org.mockito.ArgumentMatcher;18import org.mockito.ArgumentMatchers;19import org.mockito.InOrder;20import org.mockito.Mock;21import org.mockito.junit.MockitoJUnit;22import org.mockito.junit.MockitoRule;23import org.robolectric.annotation.Config;24import org.chromium.base.test.BaseRobolectricTestRunner;25import org.chromium.chrome.browser.download.DownloadInfo;26import org.chromium.chrome.browser.download.DownloadNotifier;27import org.chromium.components.offline_items_collection.ContentId;28import org.chromium.components.offline_items_collection.OfflineContentProvider;29import org.chromium.components.offline_items_collection.OfflineItem;30import org.chromium.components.offline_items_collection.OfflineItemState;31import org.chromium.components.offline_items_collection.OfflineItemVisuals;32import org.chromium.components.offline_items_collection.PendingState;33import java.util.ArrayList;34import java.util.List;35/**36 * Unit tests for {@link OfflineContentAggregatorNotifierBridgeUi}. Validate that it interacts with37 * both the {@link DownloadNotifier} and the {@link OfflineContentProvider} in expected ways.38 */39@RunWith(BaseRobolectricTestRunner.class)40@Config(manifest = Config.NONE)41public class OfflineContentAggregatorNotificationBridgeUiTest {42 /** Helper class to validate that a DownloadInfo has the right ContentId. */43 static class DownloadInfoIdMatcher implements ArgumentMatcher<DownloadInfo> {44 private final ContentId mExpectedId;45 public DownloadInfoIdMatcher(ContentId expected) {46 mExpectedId = expected;47 }48 @Override49 public boolean matches(DownloadInfo argument) {50 return ((DownloadInfo) argument).getContentId().equals(mExpectedId);51 }52 @Override53 public String toString() {54 return mExpectedId == null ? null : mExpectedId.toString();55 }56 }57 @Mock58 private OfflineContentProvider mProvider;59 @Mock60 private DownloadNotifier mNotifier;61 @Rule62 public MockitoRule mMockitoRule = MockitoJUnit.rule();63 private static OfflineItem buildOfflineItem(ContentId id, @OfflineItemState int state) {64 OfflineItem item = new OfflineItem();65 item.id = id;66 item.state = state;67 return item;68 }69 @Test70 public void testAddedItemsGetSentToTheUi() {71 OfflineContentAggregatorNotificationBridgeUi bridge =72 new OfflineContentAggregatorNotificationBridgeUi(mProvider, mNotifier);73 verify(mProvider, times(1)).addObserver(bridge);74 ArrayList<OfflineItem> items = new ArrayList<OfflineItem>() {75 {76 add(buildOfflineItem(new ContentId("1", "A"), OfflineItemState.IN_PROGRESS));77 add(buildOfflineItem(new ContentId("2", "B"), OfflineItemState.PENDING));78 add(buildOfflineItem(new ContentId("3", "C"), OfflineItemState.COMPLETE));79 add(buildOfflineItem(new ContentId("4", "D"), OfflineItemState.CANCELLED));80 add(buildOfflineItem(new ContentId("5", "E"), OfflineItemState.INTERRUPTED));81 add(buildOfflineItem(new ContentId("6", "F"), OfflineItemState.FAILED));82 add(buildOfflineItem(new ContentId("7", "G"), OfflineItemState.PAUSED));83 }84 };85 bridge.onItemsAdded(items);86 verify(mProvider, times(1)).getVisualsForItem(items.get(0).id, bridge);87 verify(mProvider, times(1)).getVisualsForItem(items.get(1).id, bridge);88 verify(mProvider, times(1)).getVisualsForItem(items.get(2).id, bridge);89 verify(mProvider, never()).getVisualsForItem(items.get(3).id, bridge);90 verify(mProvider, times(1)).getVisualsForItem(items.get(4).id, bridge);91 verify(mProvider, times(1)).getVisualsForItem(items.get(5).id, bridge);92 verify(mProvider, times(1)).getVisualsForItem(items.get(6).id, bridge);93 for (int i = 0; i < items.size(); i++) {94 bridge.onVisualsAvailable(items.get(i).id, new OfflineItemVisuals());95 }96 verify(mNotifier, times(1))97 .notifyDownloadProgress(argThat(new DownloadInfoIdMatcher(items.get(0).id)),98 ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean());99 verify(mNotifier, times(1))100 .notifyDownloadSuccessful(argThat(new DownloadInfoIdMatcher(items.get(2).id)),101 ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean(),102 ArgumentMatchers.anyBoolean());103 verify(mNotifier, times(1))104 .notifyDownloadCanceled(items.get(3).id /* OfflineItemState.CANCELLED */);105 verify(mNotifier, times(1))106 .notifyDownloadInterrupted(argThat(new DownloadInfoIdMatcher(items.get(4).id)),107 ArgumentMatchers.anyBoolean(), eq(PendingState.NOT_PENDING));108 verify(mNotifier, times(1))109 .notifyDownloadFailed(argThat(new DownloadInfoIdMatcher(items.get(5).id)));110 verify(mNotifier, times(1))111 .notifyDownloadPaused(argThat(new DownloadInfoIdMatcher(items.get(6).id)));112 bridge.destroy();113 verify(mProvider, times(1)).removeObserver(bridge);114 }115 @Test116 public void testItemUpdatesGetSentToTheUi() {117 OfflineContentAggregatorNotificationBridgeUi bridge =118 new OfflineContentAggregatorNotificationBridgeUi(mProvider, mNotifier);119 verify(mProvider, times(1)).addObserver(bridge);120 ArrayList<OfflineItem> items = new ArrayList<OfflineItem>() {121 {122 add(buildOfflineItem(new ContentId("1", "A"), OfflineItemState.IN_PROGRESS));123 add(buildOfflineItem(new ContentId("2", "B"), OfflineItemState.PENDING));124 add(buildOfflineItem(new ContentId("3", "C"), OfflineItemState.COMPLETE));125 add(buildOfflineItem(new ContentId("4", "D"), OfflineItemState.CANCELLED));126 add(buildOfflineItem(new ContentId("5", "E"), OfflineItemState.INTERRUPTED));127 add(buildOfflineItem(new ContentId("6", "F"), OfflineItemState.FAILED));128 add(buildOfflineItem(new ContentId("7", "G"), OfflineItemState.PAUSED));129 }130 };131 for (int i = 0; i < items.size(); i++) bridge.onItemUpdated(items.get(i), null);132 verify(mProvider, times(1)).getVisualsForItem(items.get(0).id, bridge);133 verify(mProvider, times(1)).getVisualsForItem(items.get(1).id, bridge);134 verify(mProvider, times(1)).getVisualsForItem(items.get(2).id, bridge);135 verify(mProvider, never()).getVisualsForItem(items.get(3).id, bridge);136 verify(mProvider, times(1)).getVisualsForItem(items.get(4).id, bridge);137 verify(mProvider, times(1)).getVisualsForItem(items.get(5).id, bridge);138 verify(mProvider, times(1)).getVisualsForItem(items.get(6).id, bridge);139 for (int i = 0; i < items.size(); i++) {140 bridge.onVisualsAvailable(items.get(i).id, new OfflineItemVisuals());141 }142 verify(mNotifier, times(1))143 .notifyDownloadProgress(argThat(new DownloadInfoIdMatcher(items.get(0).id)),144 ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean());145 verify(mNotifier, times(1))146 .notifyDownloadSuccessful(argThat(new DownloadInfoIdMatcher(items.get(2).id)),147 ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean(),148 ArgumentMatchers.anyBoolean());149 verify(mNotifier, times(1))150 .notifyDownloadCanceled(items.get(3).id /* OfflineItemState.CANCELLED */);151 verify(mNotifier, times(1))152 .notifyDownloadInterrupted(argThat(new DownloadInfoIdMatcher(items.get(4).id)),153 ArgumentMatchers.anyBoolean(), eq(PendingState.NOT_PENDING));154 verify(mNotifier, times(1))155 .notifyDownloadFailed(argThat(new DownloadInfoIdMatcher(items.get(5).id)));156 verify(mNotifier, times(1))157 .notifyDownloadPaused(argThat(new DownloadInfoIdMatcher(items.get(6).id)));158 bridge.destroy();159 verify(mProvider, times(1)).removeObserver(bridge);160 }161 @Test162 public void testNullVisuals() {163 OfflineContentAggregatorNotificationBridgeUi bridge =164 new OfflineContentAggregatorNotificationBridgeUi(mProvider, mNotifier);165 verify(mProvider, times(1)).addObserver(bridge);166 OfflineItem item1 = buildOfflineItem(new ContentId("1", "A"), OfflineItemState.IN_PROGRESS);167 OfflineItem item2 = buildOfflineItem(new ContentId("2", "B"), OfflineItemState.IN_PROGRESS);168 OfflineItemVisuals visuals1 = new OfflineItemVisuals();169 visuals1.icon = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);170 bridge.onItemUpdated(item1, null);171 bridge.onItemUpdated(item2, null);...
Source:FilesMonitorTest.java
...47 pauser.pause(3000);48 // The server should have autonomously sent some diagnostics to the client49 Mockito.verify(client)50 .publishDiagnostics(51 ArgumentMatchers.argThat(52 params ->53 params.getUri().equals(badScript.toURI().toString())54 && params.getDiagnostics().stream()55 .anyMatch(56 diagnostic ->57 diagnostic.getSeverity() == DiagnosticSeverity.Error)));58 Mockito.verify(client)59 .publishDiagnostics(60 ArgumentMatchers.argThat(61 params ->62 params.getUri().equals(goodScript.toURI().toString())63 && params.getDiagnostics().stream()64 .noneMatch(65 diagnostic ->66 diagnostic.getSeverity() == DiagnosticSeverity.Error)));67 // ---------- didOpen() test ----------68 // Reset invocations...69 Mockito.clearInvocations(client);70 DidOpenTextDocumentParams openParams =71 new DidOpenTextDocumentParams(72 new TextDocumentItem(badScript.toURI().toString(), "ash", 1, "unknown_function()"));73 proxyServer.getTextDocumentService().didOpen(openParams);74 // Wait for diagnostics...75 pauser.pause(3000);76 Mockito.verify(client)77 .publishDiagnostics(78 ArgumentMatchers.argThat(79 params ->80 params.getUri().equals(badScript.toURI().toString())81 && params.getDiagnostics().stream()82 .anyMatch(83 diagnostic ->84 diagnostic.getSeverity() == DiagnosticSeverity.Error85 && diagnostic86 .getMessage()87 .startsWith(88 "Function 'unknown_function( )' undefined."))));89 // goodScript was not changed, and so was not updated.90 Mockito.verify(client, Mockito.never())91 .publishDiagnostics(92 ArgumentMatchers.argThat(93 params -> params.getUri().equals(goodScript.toURI().toString())));94 // ---------- didChange() test ----------95 // Reset invocations...96 Mockito.clearInvocations(client);97 DidChangeTextDocumentParams changeParams =98 new DidChangeTextDocumentParams(99 new VersionedTextDocumentIdentifier(badScript.toURI().toString(), 2),100 Collections.singletonList(101 new TextDocumentContentChangeEvent("import " + goodScript.getName())));102 proxyServer.getTextDocumentService().didChange(changeParams);103 // Wait for diagnostics...104 pauser.pause(3000);105 Mockito.verify(client)106 .publishDiagnostics(107 ArgumentMatchers.argThat(108 params -> params.getUri().equals(badScript.toURI().toString())));109 // goodScript was *imported* by the new badScript, and so *was* updated.110 Mockito.verify(client)111 .publishDiagnostics(112 ArgumentMatchers.argThat(113 params -> params.getUri().equals(goodScript.toURI().toString())));114 // ---------- didChange() test, obsolete version ----------115 // Reset invocations...116 Mockito.clearInvocations(client);117 // Note how we're reverting to version 1118 changeParams =119 new DidChangeTextDocumentParams(120 new VersionedTextDocumentIdentifier(badScript.toURI().toString(), 1),121 Collections.singletonList(new TextDocumentContentChangeEvent("unknown_function()")));122 proxyServer.getTextDocumentService().didChange(changeParams);123 // Wait for diagnostics...124 pauser.pause(3000);125 // The version was lower than the one in memory, and so was ignored126 Mockito.verify(client, Mockito.never()).publishDiagnostics(ArgumentMatchers.any());127 // ---------- didClose() test ----------128 // Reset invocations...129 Mockito.clearInvocations(client);130 DidCloseTextDocumentParams closeParams =131 new DidCloseTextDocumentParams(new TextDocumentIdentifier(badScript.toURI().toString()));132 proxyServer.getTextDocumentService().didClose(closeParams);133 // Wait for diagnostics...134 pauser.pause(3000);135 // badScript should have returned to its pre-opened state.136 // goodScript, no longer imported by our version of badScript, should also have been updated.137 Mockito.verify(client)138 .publishDiagnostics(139 ArgumentMatchers.argThat(140 params ->141 params.getUri().equals(badScript.toURI().toString())142 && params.getDiagnostics().stream()143 .anyMatch(144 diagnostic ->145 diagnostic.getSeverity() == DiagnosticSeverity.Error)));146 Mockito.verify(client)147 .publishDiagnostics(148 ArgumentMatchers.argThat(149 params -> params.getUri().equals(goodScript.toURI().toString())));150 }151 @Test152 public void filesMonitorNewFileTest() {153 initialize(new InitializeParams());154 final File newScript = new File("/foo/bar/baz.ash");155 DidOpenTextDocumentParams openParams =156 new DidOpenTextDocumentParams(157 new TextDocumentItem(newScript.toURI().toString(), "ash", 1, "unknown_function()"));158 proxyServer.getTextDocumentService().didOpen(openParams);159 // Wait for diagnostics...160 pauser.pause(3000);161 // Since the content was supplied, the server doesn't care that the file doesn't exist162 Mockito.verify(client)163 .publishDiagnostics(164 ArgumentMatchers.argThat(165 params ->166 params.getUri().equals(newScript.toURI().toString())167 && params.getDiagnostics().stream()168 .anyMatch(169 diagnostic ->170 diagnostic.getSeverity() == DiagnosticSeverity.Error171 && diagnostic172 .getMessage()173 .startsWith(174 "Function 'unknown_function( )' undefined."))));175 // ---------- didClose() test ----------176 // Reset invocations...177 Mockito.clearInvocations(client);178 DidCloseTextDocumentParams closeParams =...
Source:MockitoMatchersTest.java
...27 public void testTokensEmpty() {28 StringArg obj = mock(StringArg.class);29 obj.exec("");30 ArgumentMatcher<String> matcher = MockitoMatchers.sqlMatcher(Collections.emptyList());31 verify(obj).exec(ArgumentMatchers.argThat(matcher));32 }33 @Test34 public void testTokenOneArg() {35 StringArg obj = mock(StringArg.class);36 ArgumentMatcher<String> matcher;37 obj.exec("arg1");38 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("arg1"));39 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));40 }41 @Test42 public void testInsertSql() {43 StringArg obj = mock(StringArg.class);44 ArgumentMatcher<String> matcher;45 obj.exec("insert into tableName (type, value, person_id, changed, created) values (?,?,?,?,?)");46 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("insert", "into", "tableName", "(type,", "value,",47 "person_id,", "changed,", "created)", "values", "(?,?,?,?,?)"));48 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));49 }50 @Test51 public void testTokenTwoArgs() {52 StringArg obj = mock(StringArg.class);53 ArgumentMatcher<String> matcher;54 obj.exec("arg1 arg2");55 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("arg1", "arg2"));56 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));57 }58 @Test59 public void testTokenMissingArg() {60 StringArg obj = mock(StringArg.class);61 ArgumentMatcher<String> matcher;62 obj.exec("arg1");63 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("arg1", "arg2"));64 try {65 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));66 fail("sqlMatcher should fail on missing arg2");67 } catch (AssertionError e) {68 String msg = e.getMessage();69 assertTrue("Message was: " + msg, msg.contains("\"arg1\""));70 assertTrue("Message was: " + msg, msg.contains("\"arg1 arg2\""));71 }72 }73 @Test74 public void testTokenAdditionalArg() {75 StringArg obj = mock(StringArg.class);76 ArgumentMatcher<String> matcher;77 obj.exec("arg1 arg2 arg3");78 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("arg1", "arg2"));79 try {80 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));81 fail("sqlMatcher should fail on additional arg3");82 } catch (AssertionError e) {83 String msg = e.getMessage();84 assertTrue("Message was: " + msg, msg.contains("\"arg1 arg2 arg3\""));85 assertTrue("Message was: " + msg, msg.contains("\"arg1 arg2\""));86 }87 }88 @Test89 public void testTokenWrongOrder() {90 StringArg obj = mock(StringArg.class);91 ArgumentMatcher<String> matcher;92 obj.exec("arg3 arg4");93 matcher = MockitoMatchers.sqlMatcher(Arrays.asList("arg1", "arg2"));94 try {95 verify(obj, atLeastOnce()).exec(ArgumentMatchers.argThat(matcher));96 } catch (AssertionError e) {97 String msg = e.getMessage();98 assertTrue(msg.contains("arg1"));99 assertTrue(msg.contains("arg3"));100 }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"));...
Source:NetworkTest.java
...72 network.insertItem(1, stack2, false);73 Mockito.verify(eventListener).onAttachmentChanged(74 ArgumentMatchers.eq(network),75 ArgumentMatchers.eq(0),76 ArgumentMatchers.argThat(itemStackEquals(ItemStack.EMPTY)),77 ArgumentMatchers.argThat(itemStackEquals(stack1))78 );79 Mockito.verify(eventListener).onAttachmentChanged(80 ArgumentMatchers.eq(network),81 ArgumentMatchers.eq(1),82 ArgumentMatchers.argThat(itemStackEquals(ItemStack.EMPTY)),83 ArgumentMatchers.argThat(itemStackEquals(stack2))84 );85 network.extractItem(0, false);86 Mockito.verify(eventListener).onAttachmentChanged(87 ArgumentMatchers.eq(network),88 ArgumentMatchers.eq(0),89 ArgumentMatchers.argThat(itemStackEquals(stack1)),90 ArgumentMatchers.argThat(itemStackEquals(ItemStack.EMPTY))91 );92 network.removeEventListener(eventListenerKey);93 network.extractItem(1, false);94 Mockito.verifyZeroInteractions(eventListener);95 }96}...
Source:MockitoMessageMatchers.java
...24 * <p>25 * This class contains expressive factory methods for the most common Mockito26 * matchers needed when matching {@link Message}s. If you need a different27 * matching strategy, any Hamcrest matcher can be used in Mockito through28 * {@link org.mockito.Mockito#argThat(org.mockito.ArgumentMatcher)}.29 *30 * Example usage:31 * <p>32 * With {@link org.mockito.Mockito#verify(Object)}:33 * </p>34 *35 * <pre class="code">36 * {@code37 * @Mock38 * MessageHandler handler;39 * ...40 * handler.handleMessage(message);41 * verify(handler).handleMessage(messageWithPayload(SOME_PAYLOAD));42 * verify(handler).handleMessage(messageWithPayload(is(SOME_CLASS)));43 * }44 * </pre>45 * <p>46 * With {@link org.mockito.Mockito#when(Object)}:47 * </p>48 *49 * <pre class="code">50 * {@code51 * ...52 * when(channel.send(messageWithPayload(SOME_PAYLOAD))).thenReturn(true);53 * assertThat(channel.send(message), is(true));54 * }55 * </pre>56 *57 * @author Alex Peters58 * @author Iwein Fuld59 * @author Artem Bilan60 *61 */62public final class MockitoMessageMatchers {63 private MockitoMessageMatchers() {64 }65 public static <T> Message<?> messageWithPayload(Matcher<? super T> payloadMatcher) {66 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(PayloadMatcher.hasPayload(payloadMatcher)));67 }68 public static <T> Message<?> messageWithPayload(T payload) {69 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(PayloadMatcher.hasPayload(payload)));70 }71 public static Message<?> messageWithHeaderEntry(String key, Object value) {72 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.hasHeader(key, value)));73 }74 public static Message<?> messageWithHeaderKey(String key) {75 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.hasHeaderKey(key)));76 }77 public static <T> Message<?> messageWithHeaderEntry(String key, Matcher<T> valueMatcher) {78 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.hasHeader(key, valueMatcher)));79 }80 public static Message<?> messageWithHeaderEntries(Map<String, ?> entries) {81 return ArgumentMatchers.argThat(new HamcrestArgumentMatcher<>(HeaderMatcher.hasAllHeaders(entries)));82 }83}...
Source:EventClientTest.java
...9import org.mockito.Mock;10import org.springframework.test.context.junit4.SpringRunner;11import java.net.URI;12import static org.mockito.ArgumentMatchers.any;13import static org.mockito.ArgumentMatchers.argThat;14import static org.mockito.Mockito.mock;15import static org.mockito.Mockito.verify;16import static org.mockito.Mockito.when;17@RunWith(SpringRunner.class)18public class EventClientTest {19 @Mock20 private ClientHandler clientHandler;21 @Mock22 private ClientConfig clientConfig;23 private EventClient eventClient;24 @Before25 public void before() {26 this.eventClient = new EventClient(clientConfig, clientHandler);27 this.eventClient.setRootURI("http://myuri:8080/");28 }29 @Test30 public void testRegisterEventHandler() {31 EventHandler eventHandler = mock(EventHandler.class);32 when(clientHandler.handle(argThat(argument ->33 argument.getURI().equals(URI.create("http://myuri:8080/event")))))34 .thenReturn(mock(ClientResponse.class));35 eventClient.registerEventHandler(eventHandler);36 verify(clientHandler).handle(any());37 }38 @Test39 public void testUpdateEventHandler() {40 EventHandler eventHandler = mock(EventHandler.class);41 when(clientHandler.handle(argThat(argument ->42 argument.getURI().equals(URI.create("http://myuri:8080/event")))))43 .thenReturn(mock(ClientResponse.class));44 eventClient.updateEventHandler(eventHandler);45 verify(clientHandler).handle(any());46 }47 @Test48 public void testGetEventHandlers() {49 when(clientHandler.handle(argThat(argument ->50 argument.getURI().equals(URI.create("http://myuri:8080/event/test?activeOnly=true")))))51 .thenReturn(mock(ClientResponse.class));52 eventClient.getEventHandlers("test", true);53 verify(clientHandler).handle(any());54 }55 @Test56 public void testUnregisterEventHandler() {57 when(clientHandler.handle(argThat(argument ->58 argument.getURI().equals(URI.create("http://myuri:8080/event/test")))))59 .thenReturn(mock(ClientResponse.class));60 eventClient.unregisterEventHandler("test");61 verify(clientHandler).handle(any());62 }63}...
argThat
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.ArgumentMatchers;4import org.mockito.InjectMocks;5import org.mockito.Mock;6import org.mockito.junit.MockitoJUnitRunner;7import java.util.List;8import static org.mockito.Mockito.*;9@RunWith(MockitoJUnitRunner.class)10public class MockitoTest {11 private List<String> mockList;12 private MockitoTest mockitoTest;13 public void testArgThat() {14 when(mockList.get(ArgumentMatchers.argThat(i -> i > 0))).thenReturn("test");15 System.out.println(mockList.get(1));16 }17}
argThat
Using AI Code Generation
1package com.automationrhapsody.mockito;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.ArgumentMatchers;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.junit.MockitoJUnitRunner;8import static org.mockito.ArgumentMatchers.argThat;9import static org.mockito.Mockito.when;10@RunWith(MockitoJUnitRunner.class)11public class MockitoArgThatTest {12 private Calculator calculator;13 private CalculatorService calculatorService;14 public void testArgThat() {15 when(calculator.add(argThat(new IsOddNumber()))).thenReturn(10);16 int result = calculatorService.add(3);17 System.out.println(result);18 }19}20package com.automationrhapsody.mockito;21import org.mockito.ArgumentMatcher;22public class IsOddNumber implements ArgumentMatcher<Integer> {23 public boolean matches(Integer number) {24 return number % 2 != 0;25 }26}27package com.automationrhapsody.mockito;28public class CalculatorService {29 private Calculator calculator;30 public CalculatorService(Calculator calculator) {31 this.calculator = calculator;32 }33 public int add(int number) {34 return calculator.add(number);35 }36}37package com.automationrhapsody.mockito;38public interface Calculator {39 int add(int number);40}41package com.automationrhapsody.mockito;42public class CalculatorImpl implements Calculator {43 public int add(int number) {44 return number + number;45 }46}47Related posts: Mockito – How to Use ArgumentCaptor Class Mockito – How to Use ArgumentMatchers.anyString() Method Mockito – How to Use ArgumentMatchers.anyInt() Method Mockito – How to Use ArgumentMatchers.anyList() Method Mockito – How to Use ArgumentMatchers.anyMap() Method Mockito – How to Use ArgumentMatchers.anySet() Method Mockito – How to Use ArgumentMatchers.anyCollection() Method Mockito – How to Use ArgumentMatchers.any(Class<T> clazz) Method Mockito – How to Use ArgumentMatchers.any() Method Mockito
argThat
Using AI Code Generation
1package com.automationrhapsody.junit;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.ArgumentCaptor;5import org.mockito.ArgumentMatchers;6import org.mockito.Mock;7import org.mockito.junit.MockitoJUnitRunner;8import java.util.List;9import static org.mockito.Mockito.verify;10@RunWith(MockitoJUnitRunner.class)11public class MockitoArgThatTest {12 private List<String> mockedList;13 public void testArgThat() {14 mockedList.add("one");15 ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);16 verify(mockedList).add(ArgumentMatchers.argThat(s -> s.length() > 3));17 }18}19-> at com.automationrhapsody.junit.MockitoArgThatTest.testArgThat(MockitoArgThatTest.java:19)20 someMethod(anyObject(), "raw String");21 someMethod(anyObject(), eq("String by matcher"));22 at org.mockito.internal.invocation.MatchersBinder.bindMatchers(MatchersBinder.java:83)23 at org.mockito.internal.invocation.MockitoMethodProxy$MockitoMethodInvocationHandler.invoke(MockitoMethodProxy.java:59)24 at com.sun.proxy.$Proxy9.add(Unknown Source)25 at com.automationrhapsody.junit.MockitoArgThatTest.testArgThat(MockitoArgThatTest.java:19)26This is because the method add() is overloaded, so we have to specify the type of the argument that we are going to use in the matcher. The following code fixes the problem:27package com.automationrhapsody.junit;28import org.junit.Test;29import org.junit.runner.RunWith;30import org.mockito.ArgumentCaptor;31import org.mockito.ArgumentMatchers;32import org.mockito.Mock;33import org.mockito.junit.MockitoJUnitRunner;34import java.util.List;35import static org.mockito.Mockito.verify;36@RunWith(MockitoJUnitRunner.class)37public class MockitoArgThatTest {38 private List<String> mockedList;39 public void testArgThat() {40 mockedList.add("one");
argThat
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.argThat;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.LinkedList;5import org.junit.Test;6public class MockitoTest {7 public void test() {8 LinkedList mockedList = mock(LinkedList.class);9 mockedList.add("one");10 verify(mockedList).add(argThat(new IsListOfTwoElements()));11 }12}13import org.mockito.ArgumentMatcher;14public class IsListOfTwoElements implements ArgumentMatcher {15 public boolean matches(Object list) {16 return ((LinkedList) list).size() == 2;17 }18}19org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:20mockedList.add(21);22-> at MockitoTest.test(MockitoTest.java:12)23mockedList.add(24);25-> at MockitoTest.test(MockitoTest.java:12)26import static org.mockito.ArgumentMatchers.argThat;27import static org.mockito.Mockito.mock;28import static org.mockito.Mockito.verify;29import java.util.LinkedList;30import org.junit.Test;31public class MockitoTest {32 public void test() {33 LinkedList mockedList = mock(LinkedList.class);34 mockedList.add("one");35 verify(mockedList).add(argThat(new IsListOfTwoElements()));36 }37}38import org.mockito.ArgumentMatcher;39public class IsListOfTwoElements implements ArgumentMatcher {40 public boolean matches(Object list) {41 return ((LinkedList) list).size() == 2;42 }43}44org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:45mockedList.add(46);47-> at MockitoTest.test(MockitoTest.java:12)48mockedList.add(49);50-> at MockitoTest.test(MockitoTest.java:12)
argThat
Using AI Code Generation
1package com.automationrhapsody.junit;2import static org.mockito.Mockito.*;3import java.util.List;4import org.junit.Test;5public class MockitoArgThatTest {6 public void testArgThat() {7 List mockedList = mock(List.class);8 when(mockedList.get(argThat(argument -> argument instanceof Integer && (Integer)argument > 5))).thenReturn("Hello");9 System.out.println(mockedList.get(6));10 }11}12Predicate predicate = new Predicate() {13 public boolean test(Object argument) {14 return argument instanceof Integer && (Integer)argument > 5;15 }16};17package com.automationrhapsody.junit;18import static org.mockito.Mockito.*;19import java.util.List;20import java.util.function.Predicate;21import org.junit.Test;22public class MockitoArgThatTest {23 public void testArgThat() {24 List mockedList = mock(List.class);25 Predicate predicate = new Predicate() {26 public boolean test(Object argument) {27 return argument instanceof Integer && (Integer)argument > 5;28 }29 };30 when(mockedList.get(argThat(predicate))).thenReturn("Hello");31 System.out.println(mockedList.get(6));32 }33}
argThat
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3public class MockitoExample {4 public static void main(String[] args) {5 List mockedList = Mockito.mock(List.class);6 Mockito.when(mockedList.get(Mockito.anyInt())).thenReturn("element");7 Mockito.when(mockedList.contains(ArgumentMatchers.argThat(isValid()))).thenReturn("element");8 System.out.println(mockedList.get(999));9 Mockito.verify(mockedList).get(Mockito.anyInt());10 Mockito.verify(mockedList).contains(ArgumentMatchers.argThat(s -> s.length() > 5));11 }12 private static Matcher isValid() {13 }14}
argThat
Using AI Code Generation
1package com.ack.j2se.mockito;2import java.util.List;3import org.junit.Test;4import org.mockito.ArgumentMatcher;5import static org.mockito.Mockito.*;6public class ArgumentMatchersTest {7 public void testArgThat() {8 List mockedList = mock( List.class );9 when( mockedList.get( anyInt() ) ).thenReturn( "element" );10 when( mockedList.contains( argThat( new IsValid() ) ) ).thenReturn( true );11 System.out.println( mockedList.get( 999 ) );12 verify( mockedList ).get( anyInt() );13 verify( mockedList ).contains( argThat( s -> s.length() > 5 ) );14 }15 private class IsValid extends ArgumentMatcher {16 public boolean matches( Object argument ) {17 return argument.equals( "valid" );18 }19 }20}21package com.ack.j2se.mockito;22import java.util.List;23import org.junit.Test;24import org.mockito.ArgumentMatcher;25import static org.mockito.Mockito.*;26public class ArgumentMatchersTest {27 public void testArgThat() {28 List mockedList = mock( List.class );29 when( mockedList.get( anyInt() ) ).thenReturn( "element" );30 when( mockedList.contains( argThat( new IsValid() ) ) ).thenReturn( true );31 System.out.println( mockedList.get( 999 ) );32 verify( mockedList ).get( anyInt() );33 verify( mockedList ).contains( argThat( s -> s.length() > 5 ) );34 }35 private class IsValid extends ArgumentMatcher {36 public boolean matches( Object argument ) {37 return argument.equals( "valid
argThat
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.Mockito.*;3import org.junit.*;4import org.junit.runner.*;5import org.junit.runners.*;6import static org.junit.Assert.*;7import java.util.*;8import java.util.List;9import java.util.ArrayList;10@RunWith(JUnit4.class)11public class Test1 {12 public void test1() {13 List<Integer> mockList = mock(List.class);14 when(mockList.get(anyInt())).thenReturn(1);15 when(mockList.get(argThat(new ArgumentMatcher<Integer>() {16 public boolean matches(Integer arg) {17 return arg > 10;18 }19 }))).thenReturn(2);20 assertEquals(1, mockList.get(0));21 assertEquals(1, mockList.get(1));22 assertEquals(2, mockList.get(11));23 assertEquals(2, mockList.get(12));24 }25}26import org.mockito.ArgumentMatchers;27import static org.mockito.Mockito.*;28import org.junit.*;29import org.junit.runner.*;30import org.junit.runners.*;31import static org.junit.Assert.*;32import java.util.*;33import java.util.List;34import java.util.ArrayList;35@RunWith(JUnit4.class)36public class Test2 {37 public void test1() {38 List<Integer> mockList = mock(List.class);39 when(mockList.get(anyInt())).thenReturn(1);40 when(mockList.get(argThat(new ArgumentMatcher<Integer>() {41 public boolean matches(Integer arg) {42 return arg > 10;43 }44 }))).thenReturn(2);45 assertEquals(1, mockList.get(0));46 assertEquals(1, mockList.get(1));47 assertEquals(2, mockList.get(11));48 assertEquals(2, mockList.get(12));49 }50}
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!!