How to use notNull method of org.mockito.ArgumentMatchers class

Best Mockito code snippet using org.mockito.ArgumentMatchers.notNull

Source:ArgumentMatchers.java Github

copy

Full Screen

...137 *138 * @return <code>null</code>.139 * @see #any()140 * @see #any(Class)141 * @see #notNull()142 * @see #notNull(Class)143 * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only)144 */145 @Deprecated146 public static <T> T anyObject() {147 reportMatcher(Any.ANY);148 return null;149 }150 /**151 * Matches any object of given type, excluding nulls.152 *153 * <p>154 * This matcher will perform a type check with the given type, thus excluding values.155 * See examples in javadoc for {@link ArgumentMatchers} class.156 *157 * This is an alias of: {@link #isA(Class)}}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>&#064;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>&#064;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>&#064;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>&#064;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>&#064;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.0724 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic725 * friendliness to avoid casting, this is not anymore needed in Java 8.726 */727 public static <T> Iterable<T> anyIterableOf(Class<T> clazz) {728 return anyIterable();729 }730 /**731 * <code>boolean</code> argument that is equal to the given value.732 *733 * <p>734 * See examples in javadoc for {@link ArgumentMatchers} class735 * </p>736 *737 * @param value the given value.738 * @return <code>0</code>.739 */740 public static boolean eq(boolean value) {741 reportMatcher(new Equals(value));742 return false;743 }744 /**745 * <code>byte</code> argument that is equal to the given value.746 *747 * <p>748 * See examples in javadoc for {@link ArgumentMatchers} class749 * </p>750 *751 * @param value the given value.752 * @return <code>0</code>.753 */754 public static byte eq(byte value) {755 reportMatcher(new Equals(value));756 return 0;757 }758 /**759 * <code>char</code> argument that is equal to the given value.760 *761 * <p>762 * See examples in javadoc for {@link ArgumentMatchers} class763 * </p>764 *765 * @param value the given value.766 * @return <code>0</code>.767 */768 public static char eq(char value) {769 reportMatcher(new Equals(value));770 return 0;771 }772 /**773 * <code>double</code> argument that is equal to the given value.774 *775 * <p>776 * See examples in javadoc for {@link ArgumentMatchers} class777 * </p>778 *779 * @param value the given value.780 * @return <code>0</code>.781 */782 public static double eq(double value) {783 reportMatcher(new Equals(value));784 return 0;785 }786 /**787 * <code>float</code> argument that is equal to the given value.788 *789 * <p>790 * See examples in javadoc for {@link ArgumentMatchers} class791 * </p>792 *793 * @param value the given value.794 * @return <code>0</code>.795 */796 public static float eq(float value) {797 reportMatcher(new Equals(value));798 return 0;799 }800 /**801 * <code>int</code> argument that is equal to the given value.802 *803 * <p>804 * See examples in javadoc for {@link ArgumentMatchers} class805 * </p>806 *807 * @param value the given value.808 * @return <code>0</code>.809 */810 public static int eq(int value) {811 reportMatcher(new Equals(value));812 return 0;813 }814 /**815 * <code>long</code> argument that is equal to the given value.816 *817 * <p>818 * See examples in javadoc for {@link ArgumentMatchers} class819 * </p>820 *821 * @param value the given value.822 * @return <code>0</code>.823 */824 public static long eq(long value) {825 reportMatcher(new Equals(value));826 return 0;827 }828 /**829 * <code>short</code> argument that is equal to the given value.830 * <p>831 * See examples in javadoc for {@link ArgumentMatchers} class832 *833 * @param value the given value.834 * @return <code>0</code>.835 */836 public static short eq(short value) {837 reportMatcher(new Equals(value));838 return 0;839 }840 /**841 * Object argument that is equal to the given value.842 *843 * <p>844 * See examples in javadoc for {@link ArgumentMatchers} class845 * </p>846 *847 * @param value the given value.848 * @return <code>null</code>.849 */850 public static <T> T eq(T value) {851 reportMatcher(new Equals(value));852 if (value == null)853 return null;854 return (T) Primitives.defaultValue(value.getClass());855 }856 /**857 * Object argument that is reflection-equal to the given value with support for excluding858 * selected fields from a class.859 *860 * <p>861 * This matcher can be used when equals() is not implemented on compared objects.862 * Matcher uses java reflection API to compare fields of wanted and actual object.863 * </p>864 *865 * <p>866 * Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from867 * apache commons library.868 * <p>869 * <b>Warning</b> The equality check is shallow!870 * </p>871 *872 * <p>873 * See examples in javadoc for {@link ArgumentMatchers} class874 * </p>875 *876 * @param value the given value.877 * @param excludeFields fields to exclude, if field does not exist it is ignored.878 * @return <code>null</code>.879 */880 public static <T> T refEq(T value, String... excludeFields) {881 reportMatcher(new ReflectionEquals(value, excludeFields));882 return null;883 }884 /**885 * Object argument that is the same as the given value.886 *887 * <p>888 * See examples in javadoc for {@link ArgumentMatchers} class889 * </p>890 *891 * @param <T> the type of the object, it is passed through to prevent casts.892 * @param value the given value.893 * @return <code>null</code>.894 */895 public static <T> T same(T value) {896 reportMatcher(new Same(value));897 if (value == null)898 return null;899 return (T) Primitives.defaultValue(value.getClass());900 }901 /**902 * <code>null</code> argument.903 *904 * <p>905 * See examples in javadoc for {@link ArgumentMatchers} class906 * </p>907 *908 * @return <code>null</code>.909 * @see #isNull(Class)910 * @see #isNotNull()911 * @see #isNotNull(Class)912 */913 public static <T> T isNull() {914 reportMatcher(Null.NULL);915 return null;916 }917 /**918 * <code>null</code> argument.919 *920 * <p>921 * The class argument is provided to avoid casting.922 * </p>923 *924 * <p>925 * See examples in javadoc for {@link ArgumentMatchers} class926 * </p>927 *928 * @param clazz Type to avoid casting929 * @return <code>null</code>.930 * @see #isNull()931 * @see #isNotNull()932 * @see #isNotNull(Class)933 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic934 * friendliness to avoid casting, this is not anymore needed in Java 8.935 */936 public static <T> T isNull(Class<T> clazz) {937 return isNull();938 }939 /**940 * Not <code>null</code> argument.941 *942 * <p>943 * Alias to {@link ArgumentMatchers#isNotNull()}944 * </p>945 *946 * <p>947 * See examples in javadoc for {@link ArgumentMatchers} class948 * </p>949 *950 * @return <code>null</code>.951 */952 public static <T> T notNull() {953 reportMatcher(NotNull.NOT_NULL);954 return null;955 }956 /**957 * Not <code>null</code> argument, not necessary of the given class.958 *959 * <p>960 * The class argument is provided to avoid casting.961 *962 * Alias to {@link ArgumentMatchers#isNotNull(Class)}963 * <p>964 *965 * <p>966 * See examples in javadoc for {@link ArgumentMatchers} class967 * </p>968 *969 * @param clazz Type to avoid casting970 * @return <code>null</code>.971 * @see #isNotNull()972 * @see #isNull()973 * @see #isNull(Class)974 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic975 * friendliness to avoid casting, this is not anymore needed in Java 8.976 */977 public static <T> T notNull(Class<T> clazz) {978 return notNull();979 }980 /**981 * Not <code>null</code> argument.982 *983 * <p>984 * Alias to {@link ArgumentMatchers#notNull()}985 * </p>986 *987 * <p>988 * See examples in javadoc for {@link ArgumentMatchers} class989 * </p>990 *991 * @return <code>null</code>.992 * @see #isNotNull(Class)993 * @see #isNull()994 * @see #isNull(Class)995 */996 public static <T> T isNotNull() {997 return notNull();998 }999 /**1000 * Not <code>null</code> argument, not necessary of the given class.1001 *1002 * <p>1003 * The class argument is provided to avoid casting.1004 * Alias to {@link ArgumentMatchers#notNull(Class)}1005 * </p>1006 *1007 * <p>1008 * See examples in javadoc for {@link ArgumentMatchers} class1009 * </p>1010 *1011 * @param clazz Type to avoid casting1012 * @return <code>null</code>.1013 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic1014 * friendliness to avoid casting, this is not anymore needed in Java 8.1015 */1016 public static <T> T isNotNull(Class<T> clazz) {1017 return notNull(clazz);1018 }1019 /**1020 * <code>String</code> argument that contains the given substring.1021 * <p>1022 * See examples in javadoc for {@link ArgumentMatchers} class1023 *1024 * @param substring the substring.1025 * @return empty String ("").1026 */1027 public static String contains(String substring) {1028 reportMatcher(new Contains(substring));1029 return "";1030 }1031 /**...

Full Screen

Full Screen

Source:MatchersMixin.java Github

copy

Full Screen

...294 default String matches(String regex) {295 return ArgumentMatchers.matches(regex);296 }297 /**298 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.notNull()299 * {@link org.mockito.ArgumentMatchers#notNull()}300 */301 default <T> T notNull() {302 return ArgumentMatchers.notNull();303 }304 /**305 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.nullable(java.lang.Class<T>)306 * {@link org.mockito.ArgumentMatchers#nullable(java.lang.Class)}307 */308 default <T> T nullable(Class<T> clazz) {309 return ArgumentMatchers.nullable(clazz);310 }311 /**312 * Delegate call to public static <T> T org.mockito.ArgumentMatchers.refEq(T,java.lang.String...)313 * {@link org.mockito.ArgumentMatchers#refEq(java.lang.Object,java.lang.String[])}314 */315 default <T> T refEq(T value, String... excludeFields) {316 return ArgumentMatchers.refEq(value, excludeFields);...

Full Screen

Full Screen

Source:EventsTest.java Github

copy

Full Screen

...21import static org.mockito.ArgumentMatchers.argThat;22import static org.mockito.ArgumentMatchers.eq;23import static org.mockito.ArgumentMatchers.isA;24import static org.mockito.ArgumentMatchers.isNull;25import static org.mockito.ArgumentMatchers.notNull;26import static org.mockito.Mockito.mock;27import static org.mockito.Mockito.never;28import static org.mockito.Mockito.reset;29import static org.mockito.Mockito.verify;30import static org.mockito.Mockito.when;31// NOPMD AccessorClassGeneration32@RunWith(MockitoJUnitRunner.class)33public class EventsTest {34 @Mock35 private JavascriptWebDriver driver;36 @Mock37 private WebDriver.Navigation navigation;38 @Mock39 private WebDriver.Options options;40 @Mock41 private WebDriver.Timeouts timeouts;42 private EventFiringWebDriver eventDriver;43 private ComponentInstantiator instantiator;44 private FluentAdapter fluentAdapter;45 @Before46 public void before() {47 when(driver.navigate()).thenReturn(navigation);48 when(driver.manage()).thenReturn(options);49 when(options.timeouts()).thenReturn(timeouts);50 eventDriver = new EventFiringWebDriver(driver);51 fluentAdapter = new FluentAdapter();52 fluentAdapter.initFluent(eventDriver);53 instantiator = new DefaultComponentInstantiator(fluentAdapter);54 }55 @Test56 public void testFindBy() {57 EventsRegistry eventsRegistry = new EventsRegistry(fluentAdapter);58 FindByListener beforeListener = mock(FindByListener.class);59 FindByListener afterListener = mock(FindByListener.class);60 eventsRegistry.beforeFindBy(beforeListener);61 eventsRegistry.afterFindBy(afterListener);62 WebElement element = mock(WebElement.class);63 when(driver.findElement(By.cssSelector(".test"))).thenReturn(element);64 WebElement eventElement = eventDriver.findElement(By.cssSelector(".test"));65 verify(beforeListener).on(eq(By.cssSelector(".test")), isNull(), notNull());66 verify(afterListener).on(eq(By.cssSelector(".test")), argThat(new ElementMatcher(element)), notNull());67 WebElement childElement = mock(WebElement.class);68 when(element.findElement(By.cssSelector(".test2"))).thenReturn(childElement);69 reset(beforeListener, afterListener);70 eventElement.findElement(By.cssSelector(".test2"));71 verify(beforeListener).on(eq(By.cssSelector(".test2")), argThat(new ElementMatcher(element)), notNull());72 verify(afterListener).on(eq(By.cssSelector(".test2")), argThat(new ElementMatcher(element)), notNull());73 }74 @Test75 public void testClickOn() {76 EventsRegistry eventsRegistry = new EventsRegistry(fluentAdapter);77 ElementListener beforeListener = mock(ElementListener.class);78 ElementListener afterListener = mock(ElementListener.class);79 eventsRegistry.beforeClickOn(beforeListener);80 eventsRegistry.afterClickOn(afterListener);81 WebElement element = mock(WebElement.class);82 when(driver.findElement(By.cssSelector(".test"))).thenReturn(element);83 WebElement eventElement = eventDriver.findElement(By.cssSelector(".test"));84 WebElement childElement = mock(WebElement.class);85 reset(beforeListener, afterListener);86 eventElement.click();87 verify(beforeListener).on(argThat(new ElementMatcher(element)), notNull());88 verify(afterListener).on(argThat(new ElementMatcher(element)), notNull());89 }90 @Test91 public void testChangeValueOf() {92 EventsRegistry eventsRegistry = new EventsRegistry(fluentAdapter);93 ElementListener beforeListener = mock(ElementListener.class);94 ElementListener afterListener = mock(ElementListener.class);95 eventsRegistry.beforeChangeValueOf(beforeListener);96 eventsRegistry.afterChangeValueOf(afterListener);97 WebElement element = mock(WebElement.class);98 when(driver.findElement(By.cssSelector(".test"))).thenReturn(element);99 WebElement eventElement = eventDriver.findElement(By.cssSelector(".test"));100 WebElement childElement = mock(WebElement.class);101 reset(beforeListener, afterListener);102 eventElement.sendKeys("changeValue");103 verify(beforeListener).on(argThat(new ElementMatcher(element)), notNull());104 verify(afterListener).on(argThat(new ElementMatcher(element)), notNull());105 }106 @Test107 public void testNavigate() { // NOPMD ExcessiveMethodLength108 EventsRegistry eventsRegistry = new EventsRegistry(fluentAdapter);109 assertThat(eventsRegistry.getWrappedDriver()).isSameAs(driver);110 NavigateAllListener beforeAllListener = mock(NavigateAllListener.class);111 NavigateAllListener afterAllListener = mock(NavigateAllListener.class);112 NavigateToListener beforeToListener = mock(NavigateToListener.class);113 NavigateToListener afterToListener = mock(NavigateToListener.class);114 NavigateListener beforeListener = mock(NavigateListener.class);115 NavigateListener afterListener = mock(NavigateListener.class);116 ScriptListener beforeScriptListener = mock(ScriptListener.class);117 ScriptListener afterScriptListener = mock(ScriptListener.class);118 ExceptionListener exceptionListener = mock(ExceptionListener.class);119 eventsRegistry.beforeNavigate(beforeAllListener);120 eventsRegistry.afterNavigate(afterAllListener);121 eventsRegistry.beforeNavigateBack(beforeListener);122 eventsRegistry.afterNavigateBack(afterListener);123 eventsRegistry.beforeNavigateForward(beforeListener);124 eventsRegistry.afterNavigateForward(afterListener);125 eventsRegistry.beforeNavigateRefresh(beforeListener);126 eventsRegistry.afterNavigateRefresh(afterListener);127 eventsRegistry.beforeNavigateTo(beforeToListener);128 eventsRegistry.afterNavigateTo(afterToListener);129 eventsRegistry.beforeScript(beforeScriptListener);130 eventsRegistry.afterScript(afterScriptListener);131 eventsRegistry.onException(exceptionListener);132 eventDriver.get("http://www.google.fr");133 verify(beforeAllListener)134 .on(eq("http://www.google.fr"), notNull(), isNull());135 verify(afterAllListener)136 .on(eq("http://www.google.fr"), notNull(), isNull());137 verify(beforeToListener).on(eq("http://www.google.fr"), notNull());138 verify(afterToListener).on(eq("http://www.google.fr"), notNull());139 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);140 eventDriver.navigate().to("http://www.google.fr");141 verify(beforeAllListener)142 .on(eq("http://www.google.fr"), notNull(), isNull());143 verify(afterAllListener)144 .on(eq("http://www.google.fr"), notNull(), isNull());145 verify(beforeToListener).on(eq("http://www.google.fr"), notNull());146 verify(afterToListener).on(eq("http://www.google.fr"), notNull());147 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);148 eventDriver.navigate().back();149 verify(beforeAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.BACK));150 verify(afterAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.BACK));151 verify(beforeListener).on(notNull());152 verify(afterListener).on(notNull());153 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);154 eventDriver.navigate().forward();155 verify(beforeAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.FORWARD));156 verify(afterAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.FORWARD));157 verify(beforeListener).on(notNull());158 verify(afterListener).on(notNull());159 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);160 eventDriver.navigate().refresh();161 verify(beforeAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.REFRESH));162 verify(afterAllListener).on(isNull(), notNull(), eq(NavigateAllListener.Direction.REFRESH));163 verify(beforeListener).on(notNull());164 verify(afterListener).on(notNull());165 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);166 eventDriver.executeScript("test");167 verify(beforeScriptListener).on(eq("test"), notNull());168 verify(afterScriptListener).on(eq("test"), notNull());169 reset(beforeAllListener, afterAllListener, beforeToListener, afterToListener, beforeListener, afterListener);170 when(driver.findElement(any())).thenThrow(IllegalStateException.class);171 assertThatThrownBy(() -> eventDriver.findElement(By.cssSelector(".test"))).isExactlyInstanceOf(IllegalStateException.class);172 verify(exceptionListener).on(isA(IllegalStateException.class), notNull());173 reset(exceptionListener);174 eventsRegistry.close();175 assertThatThrownBy(() -> eventDriver.findElement(By.cssSelector(".test"))).isExactlyInstanceOf(IllegalStateException.class);176 verify(exceptionListener, never()).on(isA(IllegalStateException.class), notNull());177 }178 @Test179 public void testAdapterHashcodeEquals() {180 EventListener listener = mock(EventListener.class);181 EventListener otherListener = mock(EventListener.class);182 assertThat(new EventAdapter(listener, instantiator)).isEqualTo(new EventAdapter(listener, instantiator));183 assertThat(new EventAdapter(listener, instantiator).hashCode())184 .isEqualTo(new EventAdapter(listener, instantiator).hashCode());185 assertThat(new EventAdapter(listener, instantiator)).isNotEqualTo(new EventAdapter(otherListener, instantiator));186 assertThat(new EventAdapter(listener, instantiator)).isNotEqualTo("OtherType");187 EventAdapter instance = new EventAdapter(mock(EventListener.class), instantiator);188 assertThat(instance).isEqualTo(instance);189 }190 private static final class ElementMatcher implements ArgumentMatcher<FluentWebElement> {...

Full Screen

Full Screen

Source:FreelancerRatingTest.java Github

copy

Full Screen

...17import org.thekiddos.faith.services.FreelancerRatingService;18import reactor.core.publisher.Mono;19import java.net.URI;20import static org.junit.jupiter.api.Assertions.assertEquals;21import static org.mockito.ArgumentMatchers.notNull;22@SpringBootTest23@ExtendWith( SpringExtension.class )24public class FreelancerRatingTest {25 private final FreelancerRatingService freelancerRatingService;26 private final UserRepository userRepository;27 private final FreelancerRatingRepository freelancerRatingRepository;28 private final UserMapper userMapper = UserMapper.INSTANCE;29 @MockBean30 private WebClient webClient;31 private User freelancerUser;32 private FreelancerRating freelancerRating;33 @Autowired34 public FreelancerRatingTest( FreelancerRatingService freelancerRatingService, UserRepository userRepository, FreelancerRatingRepository freelancerRatingRepository ) {35 this.freelancerRatingService = freelancerRatingService;36 this.freelancerRatingRepository = freelancerRatingRepository;37 this.userRepository = userRepository;38 }39 @BeforeEach40 void setUp() {41 freelancerRatingRepository.deleteAll();42 userRepository.deleteAll();43 this.freelancerUser = userRepository.save( getTestUser() );44 45 FreelancerRating freelancerRating = new FreelancerRating();46 freelancerRating.setId( 1L );47 freelancerRating.setFreelancer( (Freelancer) freelancerUser.getType() );48 this.freelancerRating =freelancerRating;49 // We save in test50 }51 /**52 * Test that when we try to get average rating for a freelancer that wasn't rated before we get an expected 053 */54 @Test55 void getRatingWithNoPreviousRating() {56 assertEquals( 0.0, freelancerRatingService.getRating( (Freelancer) freelancerUser.getType() ) );57 Mockito.verify( webClient, Mockito.times( 0 ) ).get();58 }59 /**60 * Test that if we have a freelancer rating then it will be fetched using an api request61 */62 @Test63 void getRating() {64 freelancerRatingRepository.save( freelancerRating );65 Rateable rateable = new Rateable();66 rateable.setId( 1L );67 rateable.setAverageRating( "2.0" );68 // TODO: we can replace this with MockWebServer69 var uriSpecMock = Mockito.mock( WebClient.RequestHeadersUriSpec.class );70 final var headersSpecMock = Mockito.mock( WebClient.RequestHeadersSpec.class );71 final var responseSpecMock = Mockito.mock( WebClient.ResponseSpec.class );72 Mockito.when( webClient.get() ).thenReturn( uriSpecMock );73 Mockito.when( uriSpecMock.uri( ArgumentMatchers.any( URI.class ) ) ).thenReturn( headersSpecMock );74 Mockito.when( headersSpecMock.header( notNull(), notNull() ) ).thenReturn( headersSpecMock );75 Mockito.when( headersSpecMock.accept( notNull() ) ).thenReturn( headersSpecMock );76 Mockito.when( headersSpecMock.retrieve() ).thenReturn( responseSpecMock );77 Mockito.when( responseSpecMock.bodyToMono( ArgumentMatchers.<Class<Rateable>>notNull() ) )78 .thenReturn( Mono.just( rateable ) );79 assertEquals( 2.0, freelancerRatingService.getRating( (Freelancer) freelancerUser.getType() ) );80 }81 // TODO: test getRating40482 /**83 * Test that we can rate a freelancer84 */85 @Test86 void rate() {87 freelancerRatingRepository.save( freelancerRating );88 var uriSpecMock = Mockito.mock( WebClient.RequestBodyUriSpec.class );89 final var headersSpecMock = Mockito.mock( WebClient.RequestBodySpec.class );90 final var requestHeadersSpecMock = Mockito.mock( WebClient.RequestHeadersSpec.class );91 final var responseSpecMock = Mockito.mock( WebClient.ResponseSpec.class );92 Mockito.when( webClient.post() ).thenReturn( uriSpecMock );93 Mockito.when( uriSpecMock.uri( ArgumentMatchers.any( URI.class ) ) ).thenReturn( headersSpecMock );94 Mockito.when( headersSpecMock.header( notNull(), notNull() ) ).thenReturn( headersSpecMock );95 Mockito.when( headersSpecMock.contentType( notNull() ) ).thenReturn( headersSpecMock );96 Mockito.when( headersSpecMock.accept( notNull() ) ).thenReturn( headersSpecMock );97 Mockito.when( headersSpecMock.body( notNull() ) ).thenReturn( requestHeadersSpecMock );98 Mockito.when( requestHeadersSpecMock.retrieve() ).thenReturn( responseSpecMock );99 Mockito.when( responseSpecMock.bodyToMono( ArgumentMatchers.<Class<String>>notNull() ) )100 .thenReturn( Mono.just( "" ) );101 freelancerRatingService.rate( (Freelancer) freelancerUser.getType(), 2 );102 Mockito.verify( webClient, Mockito.times( 1 ) ).post();103 }104 /**105 * Test that we can rate a freelancer that wasn't rated before106 */107 @Test108 void rateFirstTime() {109 Rateable rateable = new Rateable();110 rateable.setId( 1L );111 rateable.setAverageRating( "2.0" );112 var uriSpecMock = Mockito.mock( WebClient.RequestBodyUriSpec.class );113 final var headersSpecMock = Mockito.mock( WebClient.RequestBodySpec.class );114 final var requestHeadersSpecMock = Mockito.mock( WebClient.RequestHeadersSpec.class );115 final var responseSpecMock = Mockito.mock( WebClient.ResponseSpec.class );116 Mockito.when( webClient.post() ).thenReturn( uriSpecMock );117 Mockito.when( uriSpecMock.uri( ArgumentMatchers.any( URI.class ) ) ).thenReturn( headersSpecMock );118 Mockito.when( headersSpecMock.header( notNull(), notNull() ) ).thenReturn( headersSpecMock );119 Mockito.when( headersSpecMock.contentType( notNull() ) ).thenReturn( headersSpecMock );120 Mockito.when( headersSpecMock.accept( notNull() ) ).thenReturn( headersSpecMock );121 Mockito.when( headersSpecMock.body( notNull() ) ).thenReturn( requestHeadersSpecMock );122 Mockito.when( requestHeadersSpecMock.retrieve() ).thenReturn( responseSpecMock );123 Mockito.when( responseSpecMock.bodyToMono( ArgumentMatchers.<Class<String>>notNull() ) )124 .thenReturn( Mono.just( "" ) );125 Mockito.when( responseSpecMock.bodyToMono( ArgumentMatchers.<Class<Rateable>>notNull() ) )126 .thenReturn( Mono.just( rateable ) );127 freelancerRatingService.rate( (Freelancer) freelancerUser.getType(), 2 );128 assertEquals( 1, freelancerRatingRepository.findAll().size() );129 assertEquals( freelancerUser.getType(), freelancerRatingRepository.findAll().get( 0 ).getFreelancer() );130 // TODO: this is not good, but better than nothing for now.131 Mockito.verify( webClient, Mockito.times( 2 ) ).post();132 }133 // TODO: move to utils and use in all other test with defaults and option to override them134 private User getTestUser() {135 UserDto userDto = UserDto.builder().email( "freelancer@test.com" )136 .password( "password" )137 .passwordConfirm( "password" )138 .nickname( "tasty" )139 .firstName( "Test" )...

Full Screen

Full Screen

Source:PerformTransitionContextTest.java Github

copy

Full Screen

...4import static org.junit.Assert.fail;5import static org.mockito.ArgumentMatchers.any;6import static org.mockito.ArgumentMatchers.anyString;7import static org.mockito.ArgumentMatchers.eq;8import static org.mockito.ArgumentMatchers.notNull;9import static org.mockito.ArgumentMatchers.same;10import static org.mockito.ArgumentMatchers.startsWith;11import static org.mockito.Mockito.times;12import org.jceremony.PerformTransition;13import org.jceremony.bind.LifecycleFunctionalBindings;14import org.jceremony.bind.NameToFunctionBindings;15import org.jceremony.model.LifecycleFunction;16import org.jceremony.model.LifecycleModel;17import org.jceremony.model.LifecycleState;18import org.jceremony.model.PerformTransitionContext;19import org.jceremony.model.StateName;20import org.jceremony.model.Statusable;21import org.junit.Before;22import org.junit.Test;23import org.mockito.InOrder;24import org.mockito.Mockito;25public class PerformTransitionContextTest {26 LifecycleModel abcd;27 Statusable instanceAtStateA;28 LifecycleFunction mockCatchAllFunction;29 private PerformTransitionContext abcdExecutionContext;30 31 @Before32 public void setup() throws Exception {33 abcd = WellKnownLifecycles.abcdLifecycle().build();34 instanceAtStateA=Mockito.mock(Statusable.class);35 Mockito.when(instanceAtStateA.getCurrentStateName()).thenReturn(new StateName("a"));36 LifecycleFunctionalBindings bindings = Mockito.mock(LifecycleFunctionalBindings.class);37 mockCatchAllFunction=Mockito.mock(LifecycleFunction.class);38 Mockito.when(bindings.get(anyString())).thenReturn(mockCatchAllFunction);39 abcdExecutionContext=new PerformTransitionContext(instanceAtStateA, abcd, bindings);40 }41 @Test42 public void testHappyPathExecution() throws Exception {43 new PerformTransition().transitionTo(abcdExecutionContext, new StateName("b"));44 45 InOrder inOrder = Mockito.inOrder(mockCatchAllFunction, instanceAtStateA);46 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanDepartureA"), notNull(), notNull(), same(abcdExecutionContext));47 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanArrivalB1"), notNull(), notNull(), same(abcdExecutionContext));48 inOrder.verify(instanceAtStateA).setNewStatus(eq(new StateName("b")));49 inOrder.verify(mockCatchAllFunction).invoke(eq("performAfterDepartureA"), notNull(), notNull(), same(abcdExecutionContext));50 inOrder.verify(mockCatchAllFunction, times(3)).invoke(startsWith("performAfterArrivalB"), notNull(), notNull(), same(abcdExecutionContext));51 inOrder.verifyNoMoreInteractions();52 assertEquals(0, abcdExecutionContext.getExceptionDuringPerformFunctions().size());53 }54 55 @Test56 public void testWhenSecondCheckThrowsException() throws Exception{57 Exception theExceptionThrownByTheCheckFunction=new Exception("XXX");58 try{59 Mockito.doNothing().when(mockCatchAllFunction).invoke(anyString(), notNull(), notNull(), same(abcdExecutionContext));60 Mockito.doThrow(theExceptionThrownByTheCheckFunction).when(mockCatchAllFunction).invoke(eq("checkCanArrivalB1"), notNull(), notNull(), same(abcdExecutionContext));61 new PerformTransition().transitionTo(abcdExecutionContext, new StateName("b"));62 fail();63 }64 catch(Exception e){65 if(e != theExceptionThrownByTheCheckFunction) {66 fail();67 }68 }69 InOrder inOrder = Mockito.inOrder(mockCatchAllFunction, instanceAtStateA);70 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanDepartureA"), notNull(), notNull(), same(abcdExecutionContext));71 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanArrivalB1"), notNull(), notNull(), same(abcdExecutionContext));72 inOrder.verifyNoMoreInteractions();73 }74 @Test75 public void testChecksAreOkButPerformThrowsException() throws Exception{76 try{77 Mockito.doNothing().when(mockCatchAllFunction).invoke(anyString(), notNull(), notNull(), same(abcdExecutionContext));78 Mockito.doThrow(new RuntimeException("XXX")).when(mockCatchAllFunction).invoke(eq("performAfterArrivalB2"), any(), any(), same(abcdExecutionContext));79 new PerformTransition().transitionTo(abcdExecutionContext, new StateName("b"));80 }81 catch(Throwable e){82 fail();83 }84 InOrder inOrder = Mockito.inOrder(mockCatchAllFunction, instanceAtStateA);85 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanDepartureA"), notNull(), notNull(), same(abcdExecutionContext));86 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanArrivalB1"), notNull(), notNull(), same(abcdExecutionContext));87 inOrder.verify(instanceAtStateA).setNewStatus(eq(new StateName("b")));88 inOrder.verify(mockCatchAllFunction).invoke(eq("performAfterDepartureA"), notNull(), notNull(), same(abcdExecutionContext));89 inOrder.verify(mockCatchAllFunction, times(3)).invoke(startsWith("performAfterArrivalB"), notNull(), notNull(), same(abcdExecutionContext));90 inOrder.verifyNoMoreInteractions();91 assertEquals(1, abcdExecutionContext.getExceptionDuringPerformFunctions().size());92 }93 @Test94 public void testWhenPerformFunctionIsNotBoundPromotionDoesNotOccur() throws Exception {95 LifecycleModel ab = WellKnownLifecycles.abLifecycle().build();96 NameToFunctionBindings bindings=new NameToFunctionBindings();97 LifecycleFunction noop=new LifecycleFunction() {98 @Override99 public void invoke(String functionName, LifecycleState departureState, LifecycleState arrivalState, PerformTransitionContext executionContext) throws Exception {100 }101 };102 bindings.bindNameToFunction("checkCanDepartureA", noop);103 bindings.bindNameToFunction("checkCanArrivalB1", noop);104 bindings.bindNameToFunction("performAfterDepartureA", noop);105 bindings.bindNameToFunction("performAfterDepartureB1", noop);106 107 PerformTransitionContext abExecutionContext = new PerformTransitionContext(instanceAtStateA, ab, bindings);108 try {109 new PerformTransition().transitionTo(abExecutionContext, new StateName("b"));110 fail();111 } catch (Exception e) {112 assertEquals(e.getMessage(), "The function named 'performAfterArrivalB1' needs to be bound before this transition can be invoked");113 } 114 bindings.bindNameToFunction("performAfterArrivalB1", noop);115 new PerformTransition().transitionTo(abExecutionContext, new StateName("b"));116 }117 118 @Test119 public void testExcceptionDuringStatusChangeGetHandled() throws Exception {120 RuntimeException stateChangeException=new RuntimeException("Something went wrong during state change");121 try{122 Mockito.doNothing().when(mockCatchAllFunction).invoke(anyString(), notNull(), notNull(), same(abcdExecutionContext));123 Mockito.doThrow(stateChangeException).doNothing().when(instanceAtStateA).setNewStatus(any());124 new PerformTransition().transitionTo(abcdExecutionContext, new StateName("b"));125 fail();126 }127 catch(Throwable e){128 assertSame(e, stateChangeException);129 }130 131 InOrder inOrder = Mockito.inOrder(mockCatchAllFunction, instanceAtStateA);132 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanDepartureA"), notNull(), notNull(), same(abcdExecutionContext));133 inOrder.verify(mockCatchAllFunction).invoke(eq("checkCanArrivalB1"), notNull(), notNull(), same(abcdExecutionContext));134 inOrder.verify(instanceAtStateA).setNewStatus(eq(new StateName("b")));135 inOrder.verifyNoMoreInteractions();136 assertEquals(0, abcdExecutionContext.getExceptionDuringPerformFunctions().size());137 }138}...

Full Screen

Full Screen

Source:SeasonServiceTest.java Github

copy

Full Screen

...21import java.time.LocalDate;22import java.util.ArrayList;23import java.util.LinkedList;24import java.util.List;25import static org.mockito.ArgumentMatchers.notNull;26@RunWith(SpringRunner.class)27@SpringBootTest28public class SeasonServiceTest {29 private SeasonService service;30 @MockBean31 private SeasonRepository seasonRepository;32 @MockBean33 private QuarterlySeasonRepository qSeasonRepository;34 @MockBean35 private GameRepository gameRepository;36 @Before37 public void before() {38 service = new SeasonService(seasonRepository, qSeasonRepository, gameRepository);39 }40 @Test41 public void testCreateSeason() {42 // Arrange43 Season expected = Season.builder()44 .start(LocalDate.now())45 .kittyPerGame(10)46 .tocPerGame(10)47 .quarterlyTocPerGame(10)48 .quarterlyNumPayouts(3)49 .build();50 Mockito.when(seasonRepository.save((Season) notNull())).thenReturn(1);51 Mockito.when(qSeasonRepository.save((QuarterlySeason) notNull())).thenReturn(1);52 // Act53 Season actual = service.createSeason(expected);54 // Assert55 SeasonTestUtil.assertCreated(expected, actual);56 }57 @Test58 public void testGetSeason() {59 // Arrange60 Season expectedSeason = Season.builder()61 // @formatter:off62 .id(1)63 .build();64 // @formatter:on65 List<QuarterlySeason> qSeasons = new ArrayList<>(4);...

Full Screen

Full Screen

Source:ArgumentMatcherTest.java Github

copy

Full Screen

...76 });77 }78 @Test79 public void nullMatchers() {80 ArgumentMatchers.notNull(); // to samo co ArgumentMatchers.isNotNull()81 ArgumentMatchers.isNotNull(); // to samo co ArgumentMatchers.notNull()82 ArgumentMatchers.isNull();83 ArgumentMatchers.nullable(Clazz.class); // null or type84 }85 @Test86 public void anyMatchers() {87 ArgumentMatchers.any();88 ArgumentMatchers.any(String.class);89 }90 static class Clazz {91 }92}...

Full Screen

Full Screen

Source:RecaptchaServiceTest.java Github

copy

Full Screen

1package pl.maciejkopec.cms.service;2import static org.assertj.core.api.Assertions.assertThat;3import static org.mockito.ArgumentMatchers.notNull;4import static org.mockito.Mockito.mock;5import static org.mockito.Mockito.when;6import static pl.maciejkopec.cms.data.MailTestData.valid;7import java.util.Map;8import org.junit.jupiter.api.Assertions;9import org.junit.jupiter.api.BeforeEach;10import org.junit.jupiter.api.Test;11import org.junit.jupiter.api.extension.ExtendWith;12import org.mockito.ArgumentMatchers;13import org.mockito.Mock;14import org.springframework.http.HttpStatus;15import org.springframework.test.context.junit.jupiter.SpringExtension;16import org.springframework.web.reactive.function.client.WebClient;17import org.springframework.web.server.ResponseStatusException;18import reactor.core.publisher.Mono;19@ExtendWith(SpringExtension.class)20public class RecaptchaServiceTest {21 private RecaptchaService recaptchaService;22 @Mock private WebClient.ResponseSpec responseSpecMock;23 @BeforeEach24 void setUp() {25 final var webClient = mock(WebClient.class);26 final var uriSpecMock = mock(WebClient.RequestBodyUriSpec.class);27 final var headersSpecMock = mock(WebClient.RequestBodySpec.class);28 when(webClient.post()).thenReturn(uriSpecMock);29 when(uriSpecMock.uri(30 ArgumentMatchers.notNull(),31 ArgumentMatchers.<String>notNull(),32 ArgumentMatchers.<String>notNull()))33 .thenReturn(headersSpecMock);34 when(headersSpecMock.accept(notNull())).thenReturn(headersSpecMock);35 when(headersSpecMock.retrieve()).thenReturn(responseSpecMock);36 recaptchaService = new RecaptchaService(webClient, "");37 }38 @Test39 void shouldValidateToken() {40 when(responseSpecMock.bodyToMono(ArgumentMatchers.<Class<Object>>notNull()))41 .thenReturn(Mono.just(Map.of("success", true)));42 final var result = recaptchaService.validate(valid()).block();43 assertThat(result).isEqualTo(valid());44 }45 @Test46 void shouldVReturnErrorOnInvalidResponse() {47 when(responseSpecMock.bodyToMono(ArgumentMatchers.<Class<Object>>notNull()))48 .thenReturn(Mono.just(Map.of("success", false)));49 final var exception =50 Assertions.assertThrows(51 ResponseStatusException.class, () -> recaptchaService.validate(valid()).block());52 assertThat(exception.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);53 assertThat(exception.getReason()).isEqualTo("Invalid ReCaptcha token.");54 }55}...

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1import static org.mockito.ArgumentMatchers.notNull;2import java.util.ArrayList;3import java.util.List;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.Mock;7import org.mockito.junit.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class MockitoNotNullTest {10 List<String> mockList;11 public void testNotNull() {12 mockList.add("test");13 mockList.add(null);14 mockList.add("test");15 mockList.add(null);16 mockList.add("test");17 mockList.add(null);18 mockList.add(notNull(String.class));19 }20}21 at java.util.ArrayList.add(ArrayList.java:459)22 at java.util.ArrayList.add(ArrayList.java:472)23 at org.mockito.Mockito.mockingDetails(Mockito.java:1864)24 at org.mockito.internal.util.MockUtil.getMockHandler(MockUtil.java:32)25 at org.mockito.internal.util.MockUtil.getMockName(MockUtil.java:42)26 at org.mockito.internal.util.MockUtil.getMockName(MockUtil.java:37)27 at org.mockito.internal.MockitoCore.verify(MockitoCore.java:62)28 at org.mockito.Mockito.verify(Mockito.java:1935)29 at com.journaldev.MockitoNotNullTest.testNotNull(MockitoNotNullTest.java:24)30 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)31 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)32 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)33 at java.lang.reflect.Method.invoke(Method.java:498)34 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)35 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)36 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)37 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)38 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)39 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)40 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)41 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)42 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)43 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1import static org.mockito.ArgumentMatchers.notNull;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import java.util.List;5public class MockitoNotNullExample {6 public static void main(String[] args) {7 List<String> list = mock(List.class);8 when(list.get(notNull())).thenReturn("Hello");9 System.out.println(list.get(0));10 }11}

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1import static org.mockito.ArgumentMatchers.notNull;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4public class 1 {5 public static void main(String[] args) {6 MyInterface myInterface = mock(MyInterface.class);7 when(myInterface.method(notNull())).thenReturn("Hello World");8 System.out.println(myInterface.method("Hello"));9 }10}11Example 2: Mockito ArgumentMatchers notNull() method with multiple parameters12import static org.mockito.ArgumentMatchers.notNull;13import static org.mockito.Mockito.mock;14import static org.mockito.Mockito.when;15public class 2 {16 public static void main(String[] args) {17 MyInterface myInterface = mock(MyInterface.class);18 when(myInterface.method(notNull(), notNull())).thenReturn("Hello World");19 System.out.println(myInterface.method("Hello", "World"));20 }21}22Example 3: Mockito ArgumentMatchers notNull() method with null parameter23import static org.mockito.ArgumentMatchers.notNull;24import static org.mockito.Mockito.mock;25import static org.mockito.Mockito.when;26public class 3 {27 public static void main(String[] args) {28 MyInterface myInterface = mock(MyInterface.class);29 when(myInterface.method(notNull())).thenReturn("Hello World");30 System.out.println(myInterface.method(null));31 }32}33Example 4: Mockito ArgumentMatchers notNull() method with multiple parameters and null parameter34import static org.mockito.ArgumentMatchers.notNull;35import static org.mockito.Mockito.mock;36import static org.mockito.Mockito.when;37public class 4 {38 public static void main(String[] args) {

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3public class 1 {4 public static void main(String[] args) {5 Employee employee = Mockito.mock(Employee.class);6 Mockito.when(employee.getEmpName(ArgumentMatchers.notNull())).thenReturn("John");7 System.out.println(employee.getEmpName("John"));8 }9}10Example 2: ArgumentMatchers.any(Class<T> clazz) method11import org.mockito.ArgumentMatchers;12import org.mockito.Mockito;13public class 2 {14 public static void main(String[] args) {15 Employee employee = Mockito.mock(Employee.class);16 Mockito.when(employee.getEmpName(ArgumentMatchers.any(String.class))).thenReturn("John");17 System.out.println(employee.getEmpName("John"));18 }19}20Example 3: ArgumentMatchers.any() method21import org.mockito.ArgumentMatchers;22import org.mockito.Mockito;23public class 3 {24 public static void main(String[] args) {25 Employee employee = Mockito.mock(Employee.class);26 Mockito.when(employee.getEmpName(ArgumentMatchers.any())).thenReturn("John");27 System.out.println(employee.getEmpName("John"));28 }29}30Example 4: ArgumentMatchers.anyInt() method31import org.mockito.ArgumentMatchers;32import org.mockito.Mockito;33public class 4 {34 public static void main(String[] args) {35 Employee employee = Mockito.mock(Employee.class);36 Mockito.when(employee.getEmpId(ArgumentMatchers.anyInt())).thenReturn(100);37 System.out.println(employee.getEmpId(100));38 }39}40Example 5: ArgumentMatchers.anyLong() method

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1import static org.mockito.ArgumentMatchers.notNull;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4public class MockitoNotNullMethodExample {5 public static void main(String[] args) {6 Runnable runnable = mock(Runnable.class);7 runnable.run(null);8 verify(runnable).run(notNull());9 }10}11org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:12run(13);14-> at org.mockito.Mockito.verify(Mockito.java:212)15run(16);17-> at com.baeldung.mockito.MockitoNotNullMethodExample.main(MockitoNotNullMethodExample.java:16)18import static org.junit.Assert.assertEquals;19import static org.mockito.ArgumentMatchers.any;20import static org.mockito.Mockito.mock;21import static org.mockito.Mockito.verify;22import java.util.List;23import org.junit.Test;24import org.mockito.ArgumentCaptor;25public class MockitoArgumentCaptorExample {26 public void whenNotUseArgumentCaptor_thenCorrect() {27 List mockedList = mock(List.class);28 mockedList.add("one");29 verify(mockedList).add("one");30 }31 public void whenUseArgumentCaptor_thenTheSame() {32 List mockedList = mock(List.class);33 ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);34 mockedList.add("one");35 verify(mockedList).add(argument.capture());36 assertEquals("one", argument.getValue());37 }38}39org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:40list.add(41);

Full Screen

Full Screen

notNull

Using AI Code Generation

copy

Full Screen

1package com.automationtesting;2import static org.mockito.ArgumentMatchers.notNull;3import static org.mockito.Mockito.*;4import org.junit.Test;5public class MockitoNotNullTest {6 public void test() {7 InterfaceTest mock = mock(InterfaceTest.class);8 when(mock.getUniqueId()).thenReturn(43);9 System.out.println("mock.getUniqueId()="+mock.getUniqueId());10 verify(mock, times(1)).getUniqueId();11 }12}13package com.automationtesting;14public interface InterfaceTest {15 public int getUniqueId();16}17package com.automationtesting;18import org.junit.Test;19import org.mockito.Mockito;20public class MockitoTest {21 public void test() {22 InterfaceTest mock = Mockito.mock(InterfaceTest.class);23 Mockito.when(mock.getUniqueId()).thenReturn(43);24 mock.getUniqueId();25 Mockito.verify(mock).getUniqueId();26 }27}28package com.automationtesting;29import org.junit.Test;30import org.mockito.Mockito;31public class MockitoTest2 {32 public void test() {33 InterfaceTest mock = Mockito.mock(InterfaceTest.class);34 Mockito.when(mock.getUniqueId()).thenReturn(43);35 mock.getUniqueId();36 Mockito.verify(mock).getUniqueId();37 }38}39package com.automationtesting;40import org.junit.Test;41import org.mockito.Mockito;42public class MockitoTest3 {43 public void test() {44 InterfaceTest mock = Mockito.mock(InterfaceTest.class);45 Mockito.when(mock.getUniqueId()).thenReturn(43);46 mock.getUniqueId();47 Mockito.verify(mock).getUniqueId();48 }49}50package com.automationtesting;51import org.junit.Test;52import org

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful