Best Mockito code snippet using org.mockito.ArgumentMatchers.nullable
Source:ArgumentMatchers.java
...158 * </p>159 *160 * <p>161 * Since Mockito 2.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value.162 * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code>163 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito164 * 1.x.165 * </p>166 *167 * <p><strong>Notes : </strong><br/>168 * <ul>169 * <li>For primitive types use {@link #anyChar()} family.</li>170 * <li>Since Mockito 2.0 this method will perform a type check thus <code>null</code> values are not authorized.</li>171 * <li>Since mockito 2.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li>172 * </ul>173 * </p>174 *175 * @param <T> The accepted type176 * @param type the class of the accepted type.177 * @return <code>null</code>.178 * @see #any()179 * @see #anyObject()180 * @see #anyVararg()181 * @see #isA(Class)182 * @see #notNull()183 * @see #notNull(Class)184 * @see #isNull()185 * @see #isNull(Class)186 */187 public static <T> T any(Class<T> type) {188 reportMatcher(new InstanceOf.VarArgAware(type, "<any " + type.getCanonicalName() + ">"));189 return defaultValue(type);190 }191 /**192 * <code>Object</code> argument that implements the given class.193 * <p>194 * See examples in javadoc for {@link ArgumentMatchers} class195 *196 * @param <T> the accepted type.197 * @param type the class of the accepted type.198 * @return <code>null</code>.199 * @see #any(Class)200 */201 public static <T> T isA(Class<T> type) {202 reportMatcher(new InstanceOf(type));203 return defaultValue(type);204 }205 /**206 * Any vararg, meaning any number and values of arguments.207 *208 * <p>209 * Example:210 * <pre class="code"><code class="java">211 * //verification:212 * mock.foo(1, 2);213 * mock.foo(1, 2, 3, 4);214 *215 * verify(mock, times(2)).foo(anyVararg());216 *217 * //stubbing:218 * when(mock.foo(anyVararg()).thenReturn(100);219 *220 * //prints 100221 * System.out.println(mock.foo(1, 2));222 * //also prints 100223 * System.out.println(mock.foo(1, 2, 3, 4));224 * </code></pre>225 * </p>226 *227 * <p>228 * See examples in javadoc for {@link ArgumentMatchers} class.229 * </p>230 *231 * @return <code>null</code>.232 * @see #any()233 * @see #any(Class)234 * @deprecated as of 2.0 use {@link #any()}235 */236 @Deprecated237 public static <T> T anyVararg() {238 any();239 return null;240 }241 /**242 * Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code>243 *244 * <p>245 * Since Mockito 2.0, only allow valued <code>Boolean</code>, thus <code>null</code> is not anymore a valid value.246 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper247 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito248 * 1.x.249 * </p>250 *251 * <p>252 * See examples in javadoc for {@link ArgumentMatchers} class.253 * </p>254 *255 * @return <code>false</code>.256 * @see #isNull()257 * @see #isNull(Class)258 */259 public static boolean anyBoolean() {260 reportMatcher(new InstanceOf(Boolean.class, "<any boolean>"));261 return false;262 }263 /**264 * Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>.265 *266 * <p>267 * Since Mockito 2.0, only allow valued <code>Byte</code>, thus <code>null</code> is not anymore a valid value.268 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper269 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito270 * 1.x.271 * </p>272 *273 * <p>274 * See examples in javadoc for {@link ArgumentMatchers} class.275 * </p>276 *277 * @return <code>0</code>.278 * @see #isNull()279 * @see #isNull(Class)280 */281 public static byte anyByte() {282 reportMatcher(new InstanceOf(Byte.class, "<any byte>"));283 return 0;284 }285 /**286 * Any <code>char</code> or <strong>non-null</strong> <code>Character</code>.287 *288 * <p>289 * Since Mockito 2.0, only allow valued <code>Character</code>, thus <code>null</code> is not anymore a valid value.290 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper291 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito292 * 1.x.293 * </p>294 *295 * <p>296 * See examples in javadoc for {@link ArgumentMatchers} class.297 * </p>298 *299 * @return <code>0</code>.300 * @see #isNull()301 * @see #isNull(Class)302 */303 public static char anyChar() {304 reportMatcher(new InstanceOf(Character.class, "<any char>"));305 return 0;306 }307 /**308 * Any int or <strong>non-null</strong> <code>Integer</code>.309 *310 * <p>311 * Since Mockito 2.0, only allow valued <code>Integer</code>, thus <code>null</code> is not anymore a valid value.312 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper313 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito314 * 1.x.315 * </p>316 *317 * <p>318 * See examples in javadoc for {@link ArgumentMatchers} class.319 * </p>320 *321 * @return <code>0</code>.322 * @see #isNull()323 * @see #isNull(Class)324 */325 public static int anyInt() {326 reportMatcher(new InstanceOf(Integer.class, "<any integer>"));327 return 0;328 }329 /**330 * Any <code>long</code> or <strong>non-null</strong> <code>Long</code>.331 *332 * <p>333 * Since Mockito 2.0, only allow valued <code>Long</code>, thus <code>null</code> is not anymore a valid value.334 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper335 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito336 * 1.x.337 * </p>338 *339 * <p>340 * See examples in javadoc for {@link ArgumentMatchers} class.341 * </p>342 *343 * @return <code>0</code>.344 * @see #isNull()345 * @see #isNull(Class)346 */347 public static long anyLong() {348 reportMatcher(new InstanceOf(Long.class, "<any long>"));349 return 0;350 }351 /**352 * Any <code>float</code> or <strong>non-null</strong> <code>Float</code>.353 *354 * <p>355 * Since Mockito 2.0, only allow valued <code>Float</code>, thus <code>null</code> is not anymore a valid value.356 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper357 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito358 * 1.x.359 * </p>360 *361 * <p>362 * See examples in javadoc for {@link ArgumentMatchers} class.363 * </p>364 *365 * @return <code>0</code>.366 * @see #isNull()367 * @see #isNull(Class)368 */369 public static float anyFloat() {370 reportMatcher(new InstanceOf(Float.class, "<any float>"));371 return 0;372 }373 /**374 * Any <code>double</code> or <strong>non-null</strong> <code>Double</code>.375 *376 * <p>377 * Since Mockito 2.0, only allow valued <code>Double</code>, thus <code>null</code> is not anymore a valid value.378 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper379 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito380 * 1.x.381 * </p>382 *383 * <p>384 * See examples in javadoc for {@link ArgumentMatchers} class.385 * </p>386 *387 * @return <code>0</code>.388 * @see #isNull()389 * @see #isNull(Class)390 */391 public static double anyDouble() {392 reportMatcher(new InstanceOf(Double.class, "<any double>"));393 return 0;394 }395 /**396 * Any <code>short</code> or <strong>non-null</strong> <code>Short</code>.397 *398 * <p>399 * Since Mockito 2.0, only allow valued <code>Short</code>, thus <code>null</code> is not anymore a valid value.400 * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper401 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito402 * 1.x.403 * </p>404 *405 * <p>406 * See examples in javadoc for {@link ArgumentMatchers} class.407 * </p>408 *409 * @return <code>0</code>.410 * @see #isNull()411 * @see #isNull(Class)412 */413 public static short anyShort() {414 reportMatcher(new InstanceOf(Short.class, "<any short>"));415 return 0;416 }417 /**418 * Any <strong>non-null</strong> <code>String</code>419 *420 * <p>421 * Since Mockito 2.0, only allow non-null <code>String</code>.422 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper423 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito424 * 1.x.425 * </p>426 *427 * <p>428 * See examples in javadoc for {@link ArgumentMatchers} class.429 * </p>430 *431 * @return empty String ("")432 * @see #isNull()433 * @see #isNull(Class)434 */435 public static String anyString() {436 reportMatcher(new InstanceOf(String.class, "<any string>"));437 return "";438 }439 /**440 * Any <strong>non-null</strong> <code>List</code>.441 *442 * <p>443 * Since Mockito 2.0, only allow non-null <code>List</code>.444 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper445 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito446 * 1.x.447 * </p>448 *449 * <p>450 * See examples in javadoc for {@link ArgumentMatchers} class.451 * </p>452 *453 * @return empty List.454 * @see #anyListOf(Class)455 * @see #isNull()456 * @see #isNull(Class)457 */458 public static <T> List<T> anyList() {459 reportMatcher(new InstanceOf(List.class, "<any List>"));460 return new ArrayList<T>(0);461 }462 /**463 * Any <strong>non-null</strong> <code>List</code>.464 *465 * Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to466 * <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.467 *468 * <p>469 * This method doesn't do type checks of the list content with the given type parameter, it is only there470 * to avoid casting in the code.471 * </p>472 *473 * <p>474 * Since Mockito 2.0, only allow non-null <code>List</code>.475 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper476 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito477 * 1.x.478 * </p>479 *480 * <p>481 * See examples in javadoc for {@link ArgumentMatchers} class.482 * </p>483 *484 * @param clazz Type owned by the list to avoid casting485 * @return empty List.486 * @see #anyList()487 * @see #isNull()488 * @see #isNull(Class)489 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic490 * friendliness to avoid casting, this is not anymore needed in Java 8.491 */492 public static <T> List<T> anyListOf(Class<T> clazz) {493 return anyList();494 }495 /**496 * Any <strong>non-null</strong> <code>Set</code>.497 *498 * <p>499 * Since Mockito 2.0, only allow non-null <code>Set</code>.500 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper501 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito502 * 1.x.503 * </p>504 *505 * <p>506 * See examples in javadoc for {@link ArgumentMatchers} class.507 * </p>508 *509 * @return empty Set510 * @see #anySetOf(Class)511 * @see #isNull()512 * @see #isNull(Class)513 */514 public static <T> Set<T> anySet() {515 reportMatcher(new InstanceOf(Set.class, "<any set>"));516 return new HashSet<T>(0);517 }518 /**519 * Any <strong>non-null</strong> <code>Set</code>.520 *521 * <p>522 * Generic friendly alias to {@link ArgumentMatchers#anySet()}.523 * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.524 * </p>525 *526 * <p>527 * This method doesn't do type checks of the set content with the given type parameter, it is only there528 * to avoid casting in the code.529 * </p>530 *531 * <p>532 * Since Mockito 2.0, only allow non-null <code>Set</code>.533 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper534 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito535 * 1.x.536 * </p>537 *538 * <p>539 * See examples in javadoc for {@link ArgumentMatchers} class.540 * </p>541 *542 * @param clazz Type owned by the Set to avoid casting543 * @return empty Set544 * @see #anySet()545 * @see #isNull()546 * @see #isNull(Class)547 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic548 * friendliness to avoid casting, this is not anymore needed in Java 8.549 */550 public static <T> Set<T> anySetOf(Class<T> clazz) {551 return anySet();552 }553 /**554 * Any <strong>non-null</strong> <code>Map</code>.555 *556 * <p>557 * Since Mockito 2.0, only allow non-null <code>Map</code>.558 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper559 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito560 * 1.x.561 * </p>562 *563 * <p>564 * See examples in javadoc for {@link ArgumentMatchers} class.565 * </p>566 *567 * @return empty Map.568 * @see #anyMapOf(Class, Class)569 * @see #isNull()570 * @see #isNull(Class)571 */572 public static <K, V> Map<K, V> anyMap() {573 reportMatcher(new InstanceOf(Map.class, "<any map>"));574 return new HashMap<K, V>(0);575 }576 /**577 * Any <strong>non-null</strong> <code>Map</code>.578 *579 * <p>580 * Generic friendly alias to {@link ArgumentMatchers#anyMap()}.581 * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.582 * </p>583 *584 * <p>585 * This method doesn't do type checks of the map content with the given type parameter, it is only there586 * to avoid casting in the code.587 * </p>588 *589 * <p>590 * Since Mockito 2.0, only allow non-null <code>Map</code>.591 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper592 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito593 * 1.x.594 * </p>595 *596 * <p>597 * See examples in javadoc for {@link ArgumentMatchers} class.598 * </p>599 *600 * @param keyClazz Type of the map key to avoid casting601 * @param valueClazz Type of the value to avoid casting602 * @return empty Map.603 * @see #anyMap()604 * @see #isNull()605 * @see #isNull(Class)606 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic607 * friendliness to avoid casting, this is not anymore needed in Java 8.608 */609 public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {610 return anyMap();611 }612 /**613 * Any <strong>non-null</strong> <code>Collection</code>.614 *615 * <p>616 * Since Mockito 2.0, only allow non-null <code>Collection</code>.617 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>618 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito619 * 1.x.620 * </p>621 *622 * <p>623 * See examples in javadoc for {@link ArgumentMatchers} class.624 * </p>625 *626 * @return empty Collection.627 * @see #anyCollectionOf(Class)628 * @see #isNull()629 * @see #isNull(Class)630 */631 public static <T> Collection<T> anyCollection() {632 reportMatcher(new InstanceOf(Collection.class, "<any collection>"));633 return new ArrayList<T>(0);634 }635 /**636 * Any <strong>non-null</strong> <code>Collection</code>.637 *638 * <p>639 * Generic friendly alias to {@link ArgumentMatchers#anyCollection()}.640 * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.641 * </p>642 *643 * <p>644 * This method doesn't do type checks of the collection content with the given type parameter, it is only there645 * to avoid casting in the code.646 * </p>647 *648 * <p>649 * Since Mockito 2.0, only allow non-null <code>Collection</code>.650 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>651 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito652 * 1.x.653 * </p>654 *655 * <p>656 * See examples in javadoc for {@link ArgumentMatchers} class.657 * </p>658 *659 * @param clazz Type owned by the collection to avoid casting660 * @return empty Collection.661 * @see #anyCollection()662 * @see #isNull()663 * @see #isNull(Class)664 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic665 * friendliness to avoid casting, this is not anymore needed in Java 8.666 */667 public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {668 return anyCollection();669 }670 /**671 * Any <strong>non-null</strong> <code>Iterable</code>.672 *673 * <p>674 * Since Mockito 2.0, only allow non-null <code>Iterable</code>.675 * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>676 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito677 * 1.x.678 * </p>679 *680 * <p>681 * See examples in javadoc for {@link ArgumentMatchers} class.682 * </p>683 *684 * @return empty Iterable.685 * @see #anyIterableOf(Class)686 * @see #isNull()687 * @see #isNull(Class)688 * @since 2.0.0689 */690 public static <T> Iterable<T> anyIterable() {691 reportMatcher(new InstanceOf(Iterable.class, "<any iterable>"));692 return new ArrayList<T>(0);693 }694 /**695 * Any <strong>non-null</strong> <code>Iterable</code>.696 *697 * <p>698 * Generic friendly alias to {@link ArgumentMatchers#anyIterable()}.699 * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.700 * </p>701 *702 * <p>703 * This method doesn't do type checks of the iterable content with the given type parameter, it is only there704 * to avoid casting in the code.705 * </p>706 *707 * <p>708 * Since Mockito 2.0, only allow non-null <code>String</code>.709 * As strings are nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper710 * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito711 * 1.x.712 * </p>713 *714 * <p>715 * See examples in javadoc for {@link ArgumentMatchers} class.716 * </p>717 *718 * @param clazz Type owned by the collection to avoid casting719 * @return empty Iterable.720 * @see #anyIterable()721 * @see #isNull()722 * @see #isNull(Class)723 * @since 2.0.0...
Source:ConsumerImplTest.java
...18import java.io.IOException;19import java.time.Duration;20import java.util.Collections;21import java.util.concurrent.ExecutorService;22import static org.mockito.ArgumentMatchers.nullable;23public class ConsumerImplTest {24 @Mock25 private Processor processor;26 @Mock27 private TransactionEventRepository transactionEventRepository;28 @Mock29 private TransactionResultRepository transactionResultRepository;30 @Mock31 private ExecutorService executorService;32 @Mock33 private ObjectMapper objectMapper;34 @Mock35 private Logger logger;36 @Mock37 private org.apache.kafka.clients.consumer.Consumer<String, String> kafkaConsumer;38 @Mock39 private TransactionService transactionService;40 private ConsumerImpl consumer;41 @Before42 public void before() {43 MockitoAnnotations.initMocks(this);44 consumer = new ConsumerImpl(Collections.singletonList(processor), objectMapper, transactionEventRepository, transactionResultRepository, kafkaConsumer, executorService, logger, transactionService);45 Mockito.when(processor.getType()).thenReturn("P2P");46 }47 @Test48 public void testConsume_match() throws IOException {49 TransactionEvent transactionEvent = new TransactionEvent();50 transactionEvent.setId("abcd1234");51 transactionEvent.setRequest("{}");52 transactionEvent.setType("P2P");53 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(TransactionEvent.class))).thenReturn(transactionEvent);54 ConsumerRecord<String, String> consumerRecord =55 new ConsumerRecord<>(ConsumerImpl.TOPIC, 0, 0, null, new ObjectMapper().writeValueAsString(transactionEvent));56 Mockito.when(transactionEventRepository.existsById(nullable(String.class))).thenReturn(false);57 consumer.consume(consumerRecord);58 Mockito.verify(processor).process(nullable(TransactionEvent.class));59 }60 @Test61 public void testConsume_noMatch() throws IOException {62 TransactionEvent transactionEvent = new TransactionEvent();63 transactionEvent.setId("abcd1234");64 transactionEvent.setRequest("{}");65 transactionEvent.setType("create-account");66 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(TransactionEvent.class))).thenReturn(transactionEvent);67 ConsumerRecord<String, String> consumerRecord =68 new ConsumerRecord<>(ConsumerImpl.TOPIC, 0, 0, null, new ObjectMapper().writeValueAsString(transactionEvent));69 Mockito.when(transactionEventRepository.existsById(nullable(String.class))).thenReturn(false);70 consumer.consume(consumerRecord);71 Mockito.verify(processor, Mockito.never()).process(nullable(TransactionEvent.class));72 }73 @Test74 public void testConsume_InvalidBusinessRuleException() throws IOException {75 TransactionEvent transactionEvent = new TransactionEvent();76 transactionEvent.setId("abcd1234");77 transactionEvent.setRequest("{}");78 transactionEvent.setType("P2P");79 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(TransactionEvent.class))).thenReturn(transactionEvent);80 Mockito.when(transactionEventRepository.existsById(nullable(String.class))).thenReturn(false);81 ConsumerRecord<String, String> consumerRecord =82 new ConsumerRecord<>(ConsumerImpl.TOPIC, 0, 0, null, new ObjectMapper().writeValueAsString(transactionEvent));83 consumer.consume(consumerRecord);84 }85 @Test86 public void testInit() {87 Mockito.when(executorService.submit(nullable(Runnable.class))).thenReturn(null);88 consumer.init();89 }90 @Test91 public void testDestory() {92 Mockito.when(executorService.shutdownNow()).thenReturn(null);93 consumer.destroy();94 }95 @Test96 public void testRun_notRunning() {97 consumer.running = false;98 consumer.run();99 }100 @Test101 public void testRun_running() throws IOException {102 consumer.running = true;103 TransactionEvent transactionEvent = new TransactionEvent();104 transactionEvent.setId("abcd1234");105 transactionEvent.setRequest("{}");106 transactionEvent.setType("P2P");107 ConsumerRecord<String, String> consumerRecord =108 new ConsumerRecord<>(ConsumerImpl.TOPIC, 0, 0, null, new ObjectMapper().writeValueAsString(transactionEvent));109 Mockito.when(kafkaConsumer.poll(nullable(Duration.class)))110 .thenReturn(new ConsumerRecords<>(Collections.singletonMap(new TopicPartition("hello", 0), Collections.singletonList(consumerRecord))));111 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(TransactionEvent.class))).thenReturn(transactionEvent);112 Thread t1 = new Thread(() -> {113 consumer.run();114 });115 t1.start();116 t1.interrupt();117 }118}...
Source:VisibilityLoggerMixinTest.java
...17import static com.android.settingslib.core.instrumentation.Instrumentable.METRICS_CATEGORY_UNKNOWN;18import static org.mockito.ArgumentMatchers.any;19import static org.mockito.ArgumentMatchers.anyInt;20import static org.mockito.ArgumentMatchers.eq;21import static org.mockito.ArgumentMatchers.nullable;22import static org.mockito.Mockito.mock;23import static org.mockito.Mockito.never;24import static org.mockito.Mockito.times;25import static org.mockito.Mockito.verify;26import static org.mockito.Mockito.when;27import android.app.Activity;28import android.content.Context;29import android.content.Intent;30import android.os.Bundle;31import androidx.fragment.app.FragmentActivity;32import com.android.internal.logging.nano.MetricsProto;33import org.junit.Before;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.mockito.Mock;37import org.mockito.MockitoAnnotations;38import org.robolectric.Robolectric;39import org.robolectric.RobolectricTestRunner;40import org.robolectric.android.controller.ActivityController;41@RunWith(RobolectricTestRunner.class)42public class VisibilityLoggerMixinTest {43 @Mock44 private MetricsFeatureProvider mMetricsFeature;45 private VisibilityLoggerMixin mMixin;46 @Before47 public void init() {48 MockitoAnnotations.initMocks(this);49 mMixin = new VisibilityLoggerMixin(TestInstrumentable.TEST_METRIC, mMetricsFeature);50 }51 @Test52 public void shouldLogVisibleOnResume() {53 mMixin.onResume();54 verify(mMetricsFeature, times(1))55 .visible(nullable(Context.class), eq(MetricsProto.MetricsEvent.VIEW_UNKNOWN),56 eq(TestInstrumentable.TEST_METRIC));57 }58 @Test59 public void shouldLogVisibleWithSource() {60 final Intent sourceIntent = new Intent()61 .putExtra(MetricsFeatureProvider.EXTRA_SOURCE_METRICS_CATEGORY,62 MetricsProto.MetricsEvent.SETTINGS_GESTURES);63 final Activity activity = mock(Activity.class);64 when(activity.getIntent()).thenReturn(sourceIntent);65 mMixin.setSourceMetricsCategory(activity);66 mMixin.onResume();67 verify(mMetricsFeature, times(1))68 .visible(nullable(Context.class), eq(MetricsProto.MetricsEvent.SETTINGS_GESTURES),69 eq(TestInstrumentable.TEST_METRIC));70 }71 @Test72 public void shouldLogHideOnPause() {73 mMixin.onPause();74 verify(mMetricsFeature, times(1))75 .hidden(nullable(Context.class), eq(TestInstrumentable.TEST_METRIC));76 }77 @Test78 public void shouldNotLogIfMetricsFeatureIsNull() {79 mMixin = new VisibilityLoggerMixin(TestInstrumentable.TEST_METRIC, null);80 mMixin.onResume();81 mMixin.onPause();82 verify(mMetricsFeature, never())83 .hidden(nullable(Context.class), anyInt());84 }85 @Test86 public void shouldNotLogIfMetricsCategoryIsUnknown() {87 mMixin = new VisibilityLoggerMixin(METRICS_CATEGORY_UNKNOWN, mMetricsFeature);88 mMixin.onResume();89 mMixin.onPause();90 verify(mMetricsFeature, never())91 .hidden(nullable(Context.class), anyInt());92 }93 @Test94 public void activityShouldBecomeVisibleAndHide() {95 ActivityController<TestActivity> ac = Robolectric.buildActivity(TestActivity.class);96 TestActivity testActivity = ac.get();97 MockitoAnnotations.initMocks(testActivity);98 ac.create().start().resume();99 verify(testActivity.mMetricsFeatureProvider, times(1)).visible(any(), anyInt(), anyInt());100 ac.pause().stop().destroy();101 verify(testActivity.mMetricsFeatureProvider, times(1)).hidden(any(), anyInt());102 }103 public static class TestActivity extends FragmentActivity {104 @Mock105 MetricsFeatureProvider mMetricsFeatureProvider;...
Source:BidProcessorTest.java
...13import org.junit.Test;14import org.mockito.*;15import java.io.IOException;16import java.math.BigDecimal;17import static org.mockito.ArgumentMatchers.nullable;18public class BidProcessorTest {19 @Mock20 private ObjectMapper objectMapper;21 @Mock22 private AuctionService auctionService;23 @Mock24 private BidEntryService bidEntryService;25 @Mock26 private Producer producer;27 @InjectMocks28 private BidProcessor bidProcessor;29 @Before30 public void before() {31 MockitoAnnotations.initMocks(this);32 }33 @Test34 public void testProcess()throws IOException {35 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(BidRequest.class))).thenReturn(new BidRequest("vase123","johnny", BigDecimal.TEN));36 Mockito.when(auctionService.bid(nullable(BidRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));37 TransactionEvent transactionEvent = new TransactionEvent();38 transactionEvent.setId("abcd1234");39 transactionEvent.setRequest("{}");40 transactionEvent.setType(Type.BID.toString());41 bidProcessor.process(transactionEvent);42 Mockito.verify(producer).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));43 Mockito.verify(producer, Mockito.never()).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));44 }45 @Test46 public void testProcess_cannotRead() throws IOException {47 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(BidRequest.class)))48 .thenThrow(new IOException());49 Mockito.when(auctionService.bid(nullable(BidRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));50 TransactionEvent transactionEvent = new TransactionEvent();51 transactionEvent.setId("abcd1234");52 transactionEvent.setRequest("{}");53 transactionEvent.setType(Type.BID.toString());54 bidProcessor.process(transactionEvent);55 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));56 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));57 }58 @Test59 public void testProcess_serviceFail() throws IOException {60 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(BidRequest.class)))61 .thenReturn(new BidRequest("vase123","johnny", BigDecimal.TEN));62 Mockito.when(auctionService.bid(nullable(BidRequest.class))).thenThrow(new InvalidBusinessRuleException("service fail"));63 TransactionEvent transactionEvent = new TransactionEvent();64 transactionEvent.setId("abcd1234");65 transactionEvent.setRequest("{}");66 transactionEvent.setType(Type.BID.toString());67 bidProcessor.process(transactionEvent);68 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));69 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));70 }71 @Test72 public void testGetType() {73 Assert.assertEquals(Type.BID.toString(), bidProcessor.getType());74 }75}...
Source:AcceptanceProcessorTest.java
...13import org.junit.Test;14import org.mockito.*;15import java.io.IOException;16import java.math.BigDecimal;17import static org.mockito.ArgumentMatchers.nullable;18public class AcceptanceProcessorTest {19 @Mock20 private ObjectMapper objectMapper;21 @Mock22 private AuctionService auctionService;23 @Mock24 private Producer producer;25 @InjectMocks26 private AcceptanceProcessor acceptanceProcessor;27 @Before28 public void before() {29 MockitoAnnotations.initMocks(this);30 }31 @Test32 public void testProcess()throws IOException {33 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(AcceptRequest.class))).thenReturn(new AcceptRequest());34 Mockito.when(auctionService.accept(nullable(AcceptRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));35 TransactionEvent transactionEvent = new TransactionEvent();36 transactionEvent.setId("abcd1234");37 transactionEvent.setRequest("{}");38 transactionEvent.setType(Type.ACCEPTANCE.toString());39 acceptanceProcessor.process(transactionEvent);40 Mockito.verify(producer).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));41 Mockito.verify(producer, Mockito.never()).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));42 }43 @Test44 public void testProcess_cannotRead()throws IOException {45 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(AcceptRequest.class))).thenThrow(new IOException());46 Mockito.when(auctionService.accept(nullable(AcceptRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));47 TransactionEvent transactionEvent = new TransactionEvent();48 transactionEvent.setId("abcd1234");49 transactionEvent.setRequest("{}");50 transactionEvent.setType(Type.ACCEPTANCE.toString());51 acceptanceProcessor.process(transactionEvent);52 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));53 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));54 }55 @Test56 public void testProcess_serviceFail()throws IOException {57 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(AcceptRequest.class))).thenReturn(new AcceptRequest());58 Mockito.when(auctionService.accept(nullable(AcceptRequest.class))).thenThrow(new InvalidBusinessRuleException("service fail"));59 TransactionEvent transactionEvent = new TransactionEvent();60 transactionEvent.setId("abcd1234");61 transactionEvent.setRequest("{}");62 transactionEvent.setType(Type.ACCEPTANCE.toString());63 acceptanceProcessor.process(transactionEvent);64 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));65 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));66 }67 @Test68 public void testGetType() {69 Assert.assertEquals(Type.ACCEPTANCE.toString(), acceptanceProcessor.getType());70 }71}...
Source:WifiScanningRequiredFragmentTest.java
...17import static org.mockito.ArgumentMatchers.any;18import static org.mockito.ArgumentMatchers.anyInt;19import static org.mockito.ArgumentMatchers.eq;20import static org.mockito.ArgumentMatchers.isNull;21import static org.mockito.ArgumentMatchers.nullable;22import static org.mockito.Mockito.doReturn;23import static org.mockito.Mockito.never;24import static org.mockito.Mockito.spy;25import static org.mockito.Mockito.times;26import static org.mockito.Mockito.verify;27import static org.mockito.Mockito.when;28import android.content.ContentResolver;29import android.content.Context;30import android.content.DialogInterface;31import android.content.Intent;32import android.net.wifi.WifiManager;33import android.provider.Settings;34import androidx.appcompat.app.AlertDialog;35import androidx.fragment.app.Fragment;36import androidx.fragment.app.FragmentActivity;37import com.android.settings.R;38import org.junit.Before;39import org.junit.Test;40import org.junit.runner.RunWith;41import org.mockito.Mock;42import org.mockito.MockitoAnnotations;43import org.robolectric.RobolectricTestRunner;44import org.robolectric.RuntimeEnvironment;45@RunWith(RobolectricTestRunner.class)46public class WifiScanningRequiredFragmentTest {47 private WifiScanningRequiredFragment mFragment;48 private Context mContext;49 private ContentResolver mResolver;50 @Mock51 private WifiManager mWifiManager;52 @Mock53 private Fragment mCallbackFragment;54 @Mock55 private AlertDialog.Builder mBuilder;56 @Mock57 private FragmentActivity mActivity;58 @Before59 public void setUp() {60 MockitoAnnotations.initMocks(this);61 mFragment = spy(WifiScanningRequiredFragment.newInstance());62 mContext = spy(RuntimeEnvironment.application);63 when(mContext.getSystemService(WifiManager.class)).thenReturn(mWifiManager);64 mResolver = mContext.getContentResolver();65 doReturn(mActivity).when(mFragment).getActivity();66 doReturn(mContext).when(mFragment).getContext();67 mFragment.setTargetFragment(mCallbackFragment, 1000);68 when(mWifiManager.isScanAlwaysAvailable()).thenReturn(false);69 }70 @Test71 public void onClick_positiveButtonSetsWifiScanningOn()72 throws Settings.SettingNotFoundException {73 mFragment.onClick(null, DialogInterface.BUTTON_POSITIVE);74 verify(mWifiManager).setScanAlwaysAvailable(true);75 }76 @Test77 public void onClick_positiveButtonCallsBackToActivity() {78 mFragment.onClick(null, DialogInterface.BUTTON_POSITIVE);79 verify(mCallbackFragment).onActivityResult(anyInt(), anyInt(), isNull());80 }81 @Test82 public void learnMore_launchesHelpWhenIntentFound() {83 doReturn("").when(mContext).getString(eq(R.string.help_uri_wifi_scanning_required));84 mFragment.addButtonIfNeeded(mBuilder);85 verify(mBuilder, never())86 .setNeutralButton(anyInt(), nullable(DialogInterface.OnClickListener.class));87 doReturn("help").when(mContext).getString(eq(R.string.help_uri_wifi_scanning_required));88 mFragment.addButtonIfNeeded(mBuilder);89 verify(mBuilder, times(1))90 .setNeutralButton(anyInt(), nullable(DialogInterface.OnClickListener.class));91 }92 @Test93 public void learnMore_launchesHelp_shouldStartActivityForResult() {94 doReturn(new Intent()).when(mFragment).getHelpIntent(mContext);95 mFragment.addButtonIfNeeded(mBuilder);96 mFragment.onClick(null, DialogInterface.BUTTON_NEUTRAL);97 verify(mActivity, times(1)).startActivityForResult(any(), anyInt());98 }99}...
Source:OfferProcessorTest.java
...11import org.junit.Before;12import org.junit.Test;13import org.mockito.*;14import java.io.IOException;15import static org.mockito.ArgumentMatchers.nullable;16public class OfferProcessorTest {17 @Mock18 private ObjectMapper objectMapper;19 @Mock20 private AuctionService auctionService;21 @Mock22 private Producer producer;23 @InjectMocks24 private OfferProcessor offerProcessor;25 @Before26 public void before() {27 MockitoAnnotations.initMocks(this);28 }29 @Test30 public void testProcess() throws IOException {31 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(OfferRequest.class))).thenReturn(new OfferRequest("vase123","andrew"));32 Mockito.when(auctionService.offer(nullable(OfferRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));33 TransactionEvent transactionEvent = new TransactionEvent();34 transactionEvent.setId("abcd1234");35 transactionEvent.setRequest("{}");36 transactionEvent.setType(Type.OFFER.toString());37 offerProcessor.process(transactionEvent);38 Mockito.verify(producer).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));39 Mockito.verify(producer, Mockito.never()).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));40 }41 @Test42 public void testProcess_cannotRead() throws IOException {43 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(OfferRequest.class))).thenThrow(new IOException());44 Mockito.when(auctionService.offer(nullable(OfferRequest.class))).thenReturn(new AuctionItem("vase123","andrew"));45 TransactionEvent transactionEvent = new TransactionEvent();46 transactionEvent.setId("abcd1234");47 transactionEvent.setRequest("{}");48 transactionEvent.setType(Type.OFFER.toString());49 offerProcessor.process(transactionEvent);50 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));51 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));52 }53 @Test54 public void testProcess_serviceFail() throws IOException {55 Mockito.when(objectMapper.readValue(nullable(String.class), ArgumentMatchers.eq(OfferRequest.class))).thenReturn(new OfferRequest("vase123","andrew"));56 Mockito.when(auctionService.offer(nullable(OfferRequest.class))).thenThrow(new InvalidBusinessRuleException("service fail"));57 TransactionEvent transactionEvent = new TransactionEvent();58 transactionEvent.setId("abcd1234");59 transactionEvent.setRequest("{}");60 transactionEvent.setType(Type.OFFER.toString());61 offerProcessor.process(transactionEvent);62 Mockito.verify(producer, Mockito.never()).produceSuccess(nullable(String.class), nullable(Object.class), nullable(Integer.class), nullable(long.class));63 Mockito.verify(producer).produceError(nullable(String.class), nullable(InvalidBusinessRuleException.class), nullable(Integer.class), nullable(long.class));64 }65 @Test66 public void testGetType() {67 Assert.assertEquals(Type.OFFER.toString(), offerProcessor.getType());68 }69}...
Source:SystemPropPokerTest.java
...15 */16package com.android.settingslib.development;17import static org.mockito.ArgumentMatchers.any;18import static org.mockito.ArgumentMatchers.anyInt;19import static org.mockito.ArgumentMatchers.nullable;20import static org.mockito.Mockito.atLeastOnce;21import static org.mockito.Mockito.doReturn;22import static org.mockito.Mockito.never;23import static org.mockito.Mockito.verify;24import android.os.IBinder;25import android.os.Parcel;26import org.junit.Before;27import org.junit.Test;28import org.junit.runner.RunWith;29import org.mockito.Mock;30import org.mockito.MockitoAnnotations;31import org.mockito.Spy;32import org.robolectric.RobolectricTestRunner;33@RunWith(RobolectricTestRunner.class)34public class SystemPropPokerTest {35 @Spy36 private SystemPropPoker mSystemPropPoker;37 @Spy38 private SystemPropPoker.PokerTask mPokerTask;39 @Mock40 private IBinder mMockBinder;41 @Before42 public void setUp() throws Exception {43 MockitoAnnotations.initMocks(this);44 doReturn(mPokerTask).when(mSystemPropPoker).createPokerTask();45 doReturn(new String[] {"testService"}).when(mPokerTask).listServices();46 doReturn(mMockBinder).when(mPokerTask).checkService("testService");47 doReturn(true).when(mMockBinder)48 .transact(anyInt(), any(Parcel.class), nullable(Parcel.class), anyInt());49 }50 @Test51 public void testPoke() throws Exception {52 mSystemPropPoker.poke();53 verify(mMockBinder, atLeastOnce())54 .transact(anyInt(), any(Parcel.class), nullable(Parcel.class), anyInt());55 }56 @Test57 public void testPokeBlocking() throws Exception {58 mSystemPropPoker.blockPokes();59 mSystemPropPoker.poke();60 verify(mMockBinder, never())61 .transact(anyInt(), any(Parcel.class), nullable(Parcel.class), anyInt());62 mSystemPropPoker.unblockPokes();63 mSystemPropPoker.poke();64 verify(mMockBinder, atLeastOnce())65 .transact(anyInt(), any(Parcel.class), nullable(Parcel.class), anyInt());66 }67}...
nullable
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.*;2import static org.mockito.Mockito.*;3import org.mockito.Mockito;4import org.mockito.Mock;5import org.mockito.MockitoAnnotations;6import org.mockito.stubbing.Answer;7import org.mockito.stubbing.OngoingStubbing;8import org.mockito.stubbing.Stubber;9import java.util.List;10import java.util.Map;11import java.util.function.Function;12import java.util.function.Predicate;13import java.util.stream.Collectors;14import java.util.stream.Stream;15import java.util.stream.StreamSupport;16import org.junit.Test;17import org.junit.runner.RunWith;18import org.junit.runners.JUnit4;19import org.mockito.ArgumentMatcher;20import org.mockito.Mock;21import org.mockito.Mockito;22import org.mockito.MockitoAnnotations;23import org.mockito.invocation.InvocationOnMock;24import org.mockito.stubbing.Answer;25import org.mockito.stubbing.OngoingStubbing;26import org.mockito.stubbing.Stubber;27import java.util.List;28import java.util.Map;29import java.util.function.Function;30import java.util.function.Predicate;31import java.util.stream.Collectors;32import java.util.stream.Stream;33import java.util.stream.StreamSupport;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.junit.runners.JUnit4;37import org.mockito.ArgumentMatcher;38import org.mockito.Mock;39import org.mockito.Mockito;40import org.mockito.MockitoAnnotations;41import org.mockito.invocation.InvocationOnMock;42import org.mockito.stubbing.Answer;43import org.mockito.stubbing.OngoingStubbing;44import org.mockito.stubbing.Stubber;45import java.util.List;46import java.util.Map;47import java.util.function.Function;48import java.util.function.Predicate;49import java.util.stream.Collectors;50import java.util.stream.Stream;51import java.util.stream.StreamSupport;52import org.junit.Test;53import org.junit.runner.RunWith;54import org.junit.runners.JUnit4;55import org.mockito.ArgumentMatcher;56import org.mockito.Mock;57import org.mockito.Mockito;58import org.mockito.MockitoAnnotations;59import org.mockito.invocation.InvocationOnMock;60import org.mockito.stubbing.Answer;61import org.mockito.stubbing.OngoingStubbing;62import org.mockito.stubbing.Stubber;63import java.util.List;64import java.util.Map;65import java.util.function.Function;66import java.util.function.Predicate;67import java.util.stream.Collectors;68import java.util.stream.Stream;69import java.util.stream.StreamSupport;70import org.junit.Test;71import org.junit.runner.RunWith;72import org.junit.runners.JUnit4;73import org.mockito.ArgumentMatcher;74import org.mockito.Mock;75import org.mockito.Mockito;76import org.mockito.MockitoAnnotations;77import org.mockito.invocation.Invocation
nullable
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4import java.util.ArrayList;5public class Test {6 public static void main(String[] args) {7 List<String> mockedList = Mockito.mock(ArrayList.class);8 Mockito.when(mockedList.get(ArgumentMatchers.<Integer>nullable())).thenReturn("foo");9 System.out.println(mockedList.get(null));10 }11}
nullable
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4import java.util.ArrayList;5public class Test {6 public static void main(String[] args) {7 List<String> mockedList = Mockito.mock(ArrayList.class);8 Mockito.when(mockedList.get(ArgumentMatchers.anyInt()))9 .thenReturn("foo");10 Mockito.when(mockedList.get(ArgumentMatchers.isNull()))11 .thenReturn("bar");12 System.out.println(mockedList.get(1));13 System.out.println(mockedList.get(null));14 }15}16How to use ArgumentCaptor.capture() in Mockito?17How to use ArgumentCaptor.forClass() in Mockito?18How to use ArgumentCaptor.getValue() in Mockito?19How to use ArgumentCaptor.getAllValues() in Mockito?20How to use ArgumentCaptor.getValues() in Mockito?21How to use ArgumentCaptor.capture() in Mockito?22How to use ArgumentCaptor.getAllValues() in Mockito?23How to use ArgumentCaptor.forClass() in Mockito?24How to use ArgumentCaptor.getValue() in Mockito?25How to use ArgumentCaptor.getValues() in Mockito?26How to use ArgumentCaptor.capture() in Mockito?27How to use ArgumentCaptor.getAllValues() in Mockito?28How to use ArgumentCaptor.forClass() in Mockito?29How to use ArgumentCaptor.getValue() in Mockito?30How to use ArgumentCaptor.getValues() in Mockito?31How to use ArgumentCaptor.capture() in Mockito?32How to use ArgumentCaptor.getAllValues() in Mockito?33How to use ArgumentCaptor.forClass() in Mockito?34How to use ArgumentCaptor.getValue() in Mockito?35How to use ArgumentCaptor.getValues() in Mockito?36How to use ArgumentCaptor.capture() in Mockito?37How to use ArgumentCaptor.getAllValues() in Mockito?38How to use ArgumentCaptor.forClass() in Mockito?39How to use ArgumentCaptor.getValue() in Mockito
nullable
Using AI Code Generation
1public class Test {2 public void test() {3 List<String> mockList = mock(List.class);4 when(mockList.get(anyInt())).thenReturn("Hello");5 when(mockList.get(anyInt())).thenReturn(null);6 }7}8public class Test {9 public void test() {10 List<String> mockList = mock(List.class);11 when(mockList.get(anyInt())).thenReturn("Hello");12 when(mockList.get(nullable(Integer.class))).thenReturn(null);13 }14}15public class Test {16 public void test() {17 List<String> mockList = mock(List.class);18 when(mockList.get(anyInt())).thenReturn("Hello");19 when(mockList.get(isNull())).thenReturn(null);20 }21}22public class Test {23 public void test() {24 List<String> mockList = mock(List.class);25 when(mockList.get(anyInt())).thenReturn("Hello");26 when(mockList.get(isA(Integer.class))).thenReturn(null);27 }28}29public class Test {30 public void test() {31 List<String> mockList = mock(List.class);32 when(mockList.get(anyInt())).thenReturn("Hello");33 when(mockList.get(argThat(x -> x == null))).thenReturn(null);34 }35}36public class Test {37 public void test() {38 List<String> mockList = mock(List.class);39 when(mockList.get(anyInt())).thenReturn("Hello");40 when(mockList.get(argThat(x -> x != null))).thenReturn(null);
nullable
Using AI Code Generation
1package com.example;2import static org.mockito.ArgumentMatchers.*;3import static org.mockito.Mockito.*;4import java.util.ArrayList;5import java.util.List;6public class Test {7 public static void main(String[] args) {8 List<String> mockedList = mock(ArrayList.class);9 when(mockedList.get(anyInt())).thenReturn("element");10 System.out.println(mockedList.get(999));11 }12}13ArgumentCaptor <argumentType> argumentCaptor = ArgumentCaptor.forClass(argumentType.class);14package com.example;15import static org.mockito.ArgumentMatchers.*;16import static org.mockito.Mockito.*;17import java.util.ArrayList;18import java.util.List;19import org.mockito.ArgumentCaptor;20public class Test {21 public static void main(String[] args) {22 List<String> mockedList = mock(ArrayList.class);23 when(mockedList.get(anyInt())).thenReturn("element");24 System.out.println(mockedList.get(999));25 ArgumentCaptor<Integer> argumentCaptor = ArgumentCaptor.forClass(Integer.class);26 verify(mockedList).get(argumentCaptor.capture());27 System.out.println(argumentCaptor.getValue());28 }29}30@RunWith(MockitoJUnitRunner.class)31public class Test {32 private List<String> mockedList;33}34package com.example;35import static org.mockito.ArgumentMatchers.*;36import static org.mockito.Mockito.*;37import java.util.ArrayList;38import java.util.List;39import org.junit.Test;40import org.junit.runner.RunWith;41import org.mockito.ArgumentCaptor;42import org.mockito.InjectMocks
nullable
Using AI Code Generation
1package org.mockito;2import org.junit.Test;3import static org.mockito.Mockito.*;4import static org.mockito.ArgumentMatchers.*;5public class MockitoTest {6 public void test1() {7 Foo foo = mock(Foo.class);8 when(foo.bar(nullable(String.class))).thenReturn("Hello");9 foo.bar("Hello");10 verify(foo).bar("Hello");11 }12}13package org.mockito;14import org.junit.Test;15import static org.mockito.Mockito.*;16import static org.mockito.ArgumentMatchers.*;17public class MockitoTest {18 public void test2() {19 Foo foo = mock(Foo.class);20 when(foo.bar(anyString())).thenReturn("Hello");21 foo.bar("Hello");22 verify(foo).bar("Hello");23 }24}25package org.mockito;26import org.junit.Test;27import static org.mockito.Mockito.*;28import static org.mockito.ArgumentMatchers.*;29public class MockitoTest {30 public void test3() {31 Foo foo = mock(Foo.class);32 when(foo.bar(isNull())).thenReturn("Hello");33 foo.bar(null);34 verify(foo).bar(null);35 }36}37package org.mockito;38import org.junit.Test;39import static org.mockito.Mockito.*;40import static org.mockito.ArgumentMatchers.*;41public class MockitoTest {42 public void test4() {43 Foo foo = mock(Foo.class);44 when(foo.bar(isNotNull())).thenReturn("Hello");45 foo.bar("Hello");46 verify(foo).bar("Hello");47 }48}49package org.mockito;50import org.junit.Test;51import static org.mockito.Mockito.*;52import static org.mockito.ArgumentMatchers.*;53public class MockitoTest {54 public void test5() {55 Foo foo = mock(Foo.class);56 when(foo.bar(notNull())).thenReturn("Hello");57 foo.bar("Hello");58 verify(foo).bar("Hello");59 }60}61package org.mockito;62import org.junit.Test;63import static org.mockito.Mockito.*;64import static org.mockito
nullable
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import org.mockito.stubbing.Answer;4class A {5 public static void main(String[] args) {6 Mockito.mock(A.class, (Answer) invocation -> {7 return ArgumentMatchers.nullable(String.class);8 });9 }10}11import org.mockito.ArgumentMatchers;12import org.mockito.Mockito;13import org.mockito.stubbing.Answer;14class A {15 public static void main(String[] args) {16 Mockito.mock(A.class, (Answer) invocation -> {17 return ArgumentMatchers.nullable(String.class);18 });19 }20}21import org.mockito.ArgumentMatchers;22import org.mockito.Mockito;23import org.mockito.stubbing.Answer;24class A {25 public static void main(String[] args) {26 Mockito.mock(A.class, (Answer) invocation -> {27 return ArgumentMatchers.nullable(String.class);28 });29 }30}31import org.mockito.ArgumentMatchers;32import org.mockito.Mockito;33import org.mockito.stubbing.Answer;34class A {35 public static void main(String[] args) {36 Mockito.mock(A.class, (Answer) invocation -> {37 return ArgumentMatchers.nullable(String.class);38 });39 }40}41import org.mockito.ArgumentMatchers;42import org.mockito.Mockito;43import org.mockito.stubbing.Answer;44class A {45 public static void main(String[] args) {46 Mockito.mock(A.class, (Answer) invocation -> {47 return ArgumentMatchers.nullable(String.class);48 });49 }50}51import org.mockito.ArgumentMatchers;52import org.mockito.Mockito;53import org.mockito.stubbing.Answer;54class A {55 public static void main(String[] args) {
nullable
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import static org.mockito.Mockito.*;3class Test {4 void test() {5 List mockList = mock(List.class);6 when(mockList.get(ArgumentMatchers.<Integer>nullable())).thenReturn("foo");7 verify(mockList).get(ArgumentMatchers.<Integer>nullable());8 }9}10 <property name="message" value="Line matches the illegal pattern '{0}'."/>
nullable
Using AI Code Generation
1import static org.mockito.ArgumentMatchers.nullable;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.List;5public class 1 {6 public static void main(String[] args) {7 List mockedList = mock(List.class);8 mockedList.add(nullable(String.class));9 verify(mockedList).add(nullable(String.class));10 }11}12org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:13list.add(14);15-> at 1.main(1.java:15)16list.add(17);18-> at 1.main(1.java:16)19at org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.create(ArgumentsAreDifferent.java:43)20at org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.create(ArgumentsAreDifferent.java:33)21at org.mockito.internal.verification.junit.ArgumentsAreDifferentReporter.wrongArguments(ArgumentsAreDifferentReporter.java:36)22at org.mockito.internal.verification.junit.JUnitArgumentMatcher.safeReport(JUnitArgumentMatcher.java:36)23at org.mockito.internal.verification.junit.JUnitArgumentMatcher.matches(JUnitArgumentMatcher.java:24)24at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:98)25at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)26at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)27at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:62)28at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:47)29at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:109)30at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:101)31at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.intercept(MockMethodInterceptor.java:85)32at java.util.List.add(List.java)33at 1.main(1.java:16)
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!!