Best Mockito code snippet using org.mockito.internal.util.JavaEightUtil
Source: ReturnsEmptyValues.java
...19import java.util.SortedMap;20import java.util.SortedSet;21import java.util.TreeMap;22import java.util.TreeSet;23import org.mockito.internal.util.JavaEightUtil;24import org.mockito.internal.util.MockUtil;25import org.mockito.internal.util.Primitives;26import org.mockito.invocation.InvocationOnMock;27import org.mockito.mock.MockName;28import org.mockito.stubbing.Answer;29/**30 * Default answer of every Mockito mock.31 * <ul>32 * <li>33 * Returns appropriate primitive for primitive-returning methods34 * </li>35 * <li>36 * Returns consistent values for primitive wrapper classes (e.g. int-returning method returns 0 <b>and</b> Integer-returning method returns 0, too)37 * </li>38 * <li>39 * Returns empty collection for collection-returning methods (works for most commonly used collection types)40 * </li>41 * <li>42 * Returns description of mock for toString() method43 * </li>44 * <li>45 * Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)46 * </li>47 * <li>48 * Returns an {@code java.util.Optional#empty() empty Optional} for Optional. Similarly for primitive optional variants.49 * </li>50 * <li>51 * Returns an {@code java.util.stream.Stream#empty() empty Stream} for Stream. Similarly for primitive stream variants.52 * </li>53 * <li>54 * Returns an {@code java.time.Duration.ZERO zero Duration} for empty Duration and {@code java.time.Period.ZERO zero Period} for empty Period.55 * </li>56 * <li>57 * Returns null for everything else58 * </li>59 * </ul>60 */61public class ReturnsEmptyValues implements Answer<Object>, Serializable {62 private static final long serialVersionUID = 1998191268711234347L;63 /* (non-Javadoc)64 * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)65 */66 @Override67 public Object answer(InvocationOnMock invocation) {68 if (isToStringMethod(invocation.getMethod())) {69 Object mock = invocation.getMock();70 MockName name = MockUtil.getMockName(mock);71 if (name.isDefault()) {72 return "Mock for "73 + MockUtil.getMockSettings(mock).getTypeToMock().getSimpleName()74 + ", hashCode: "75 + mock.hashCode();76 } else {77 return name.toString();78 }79 } else if (isCompareToMethod(invocation.getMethod())) {80 // see issue 184.81 // mocks by default should return 0 if references are the same, otherwise some other82 // value because they are not the same. Hence we return 1 (anything but 0 is good).83 // Only for compareTo() method by the Comparable interface84 return invocation.getMock() == invocation.getArgument(0) ? 0 : 1;85 }86 Class<?> returnType = invocation.getMethod().getReturnType();87 return returnValueFor(returnType);88 }89 Object returnValueFor(Class<?> type) {90 if (Primitives.isPrimitiveOrWrapper(type)) {91 return Primitives.defaultValue(type);92 // new instances are used instead of Collections.emptyList(), etc.93 // to avoid UnsupportedOperationException if code under test modifies returned94 // collection95 } else if (type == Iterable.class) {96 return new ArrayList<>(0);97 } else if (type == Collection.class) {98 return new LinkedList<>();99 } else if (type == Set.class) {100 return new HashSet<>();101 } else if (type == HashSet.class) {102 return new HashSet<>();103 } else if (type == SortedSet.class) {104 return new TreeSet<>();105 } else if (type == TreeSet.class) {106 return new TreeSet<>();107 } else if (type == LinkedHashSet.class) {108 return new LinkedHashSet<>();109 } else if (type == List.class) {110 return new LinkedList<>();111 } else if (type == LinkedList.class) {112 return new LinkedList<>();113 } else if (type == ArrayList.class) {114 return new ArrayList<>();115 } else if (type == Map.class) {116 return new HashMap<>();117 } else if (type == HashMap.class) {118 return new HashMap<>();119 } else if (type == SortedMap.class) {120 return new TreeMap<>();121 } else if (type == TreeMap.class) {122 return new TreeMap<>();123 } else if (type == LinkedHashMap.class) {124 return new LinkedHashMap<>();125 } else if ("java.util.Optional".equals(type.getName())) {126 return JavaEightUtil.emptyOptional();127 } else if ("java.util.OptionalDouble".equals(type.getName())) {128 return JavaEightUtil.emptyOptionalDouble();129 } else if ("java.util.OptionalInt".equals(type.getName())) {130 return JavaEightUtil.emptyOptionalInt();131 } else if ("java.util.OptionalLong".equals(type.getName())) {132 return JavaEightUtil.emptyOptionalLong();133 } else if ("java.util.stream.Stream".equals(type.getName())) {134 return JavaEightUtil.emptyStream();135 } else if ("java.util.stream.DoubleStream".equals(type.getName())) {136 return JavaEightUtil.emptyDoubleStream();137 } else if ("java.util.stream.IntStream".equals(type.getName())) {138 return JavaEightUtil.emptyIntStream();139 } else if ("java.util.stream.LongStream".equals(type.getName())) {140 return JavaEightUtil.emptyLongStream();141 } else if ("java.time.Duration".equals(type.getName())) {142 return JavaEightUtil.emptyDuration();143 } else if ("java.time.Period".equals(type.getName())) {144 return JavaEightUtil.emptyPeriod();145 }146 // Let's not care about the rest of collections.147 return null;148 }149}
Source: MutinyAnswer.java
...18import java.util.SortedSet;19import java.util.TreeMap;20import java.util.TreeSet;21import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;22import org.mockito.internal.util.JavaEightUtil;23import org.mockito.internal.util.Primitives;24import org.mockito.invocation.InvocationOnMock;25import io.smallrye.mutiny.Multi;26import io.smallrye.mutiny.Uni;27@SuppressWarnings("serial")28public class MutinyAnswer extends ReturnsEmptyValues {29 @Override30 public Object answer(InvocationOnMock inv) {31 if (isToStringMethod(inv.getMethod())32 || isCompareToMethod(inv.getMethod())) {33 return super.answer(inv);34 }35 Class<?> returnType = inv.getMethod().getReturnType();36 // save the user some time figuring out this issue when it happens37 if ((returnType.getName().equals(Multi.class.getName()) && returnType != Multi.class)38 || (returnType.getName().equals(Uni.class.getName()) && returnType != Uni.class)) {39 throw new IllegalStateException("Class loader issue: we have two Multi classes with different class loaders. "40 + "Make sure to initialize this class with the QuarkusClassLoader.");41 }42 if (returnType == Multi.class) {43 return Multi.createFrom().item(returnValueForMutiny(inv.getMethod().getGenericReturnType()));44 } else if (returnType == Uni.class) {45 return Uni.createFrom().item(returnValueForMutiny(inv.getMethod().getGenericReturnType()));46 }47 return returnValueForClass(returnType);48 }49 private Object returnValueForMutiny(Type uniOrMultiType) {50 // check for raw types51 if (uniOrMultiType instanceof Class)52 return returnValueForClass(Object.class);53 Type ret = ((ParameterizedType) uniOrMultiType).getActualTypeArguments()[0];54 return returnValueForType(ret);55 }56 private Object returnValueForType(Type type) {57 if (type instanceof Class)58 return returnValueForClass((Class<?>) type);59 if (type instanceof ParameterizedType)60 return returnValueForClass((Class<?>) ((ParameterizedType) type).getRawType());61 if (type instanceof TypeVariable) {62 TypeVariable<?> tv = (TypeVariable<?>) type;63 // default upper bound is Object so we always have a value64 return returnValueForType(tv.getBounds()[0]);65 }66 return returnValueForClass(Object.class);67 }68 // copied from supertype due to access restriction :(69 Object returnValueForClass(Class<?> type) {70 if (Primitives.isPrimitiveOrWrapper(type)) {71 return Primitives.defaultValue(type);72 //new instances are used instead of Collections.emptyList(), etc.73 //to avoid UnsupportedOperationException if code under test modifies returned collection74 } else if (type == Iterable.class) {75 return new ArrayList<Object>(0);76 } else if (type == Collection.class) {77 return new LinkedList<Object>();78 } else if (type == Set.class) {79 return new HashSet<Object>();80 } else if (type == HashSet.class) {81 return new HashSet<Object>();82 } else if (type == SortedSet.class) {83 return new TreeSet<Object>();84 } else if (type == TreeSet.class) {85 return new TreeSet<Object>();86 } else if (type == LinkedHashSet.class) {87 return new LinkedHashSet<Object>();88 } else if (type == List.class) {89 return new LinkedList<Object>();90 } else if (type == LinkedList.class) {91 return new LinkedList<Object>();92 } else if (type == ArrayList.class) {93 return new ArrayList<Object>();94 } else if (type == Map.class) {95 return new HashMap<Object, Object>();96 } else if (type == HashMap.class) {97 return new HashMap<Object, Object>();98 } else if (type == SortedMap.class) {99 return new TreeMap<Object, Object>();100 } else if (type == TreeMap.class) {101 return new TreeMap<Object, Object>();102 } else if (type == LinkedHashMap.class) {103 return new LinkedHashMap<Object, Object>();104 } else if ("java.util.Optional".equals(type.getName())) {105 return JavaEightUtil.emptyOptional();106 } else if ("java.util.OptionalDouble".equals(type.getName())) {107 return JavaEightUtil.emptyOptionalDouble();108 } else if ("java.util.OptionalInt".equals(type.getName())) {109 return JavaEightUtil.emptyOptionalInt();110 } else if ("java.util.OptionalLong".equals(type.getName())) {111 return JavaEightUtil.emptyOptionalLong();112 } else if ("java.util.stream.Stream".equals(type.getName())) {113 return JavaEightUtil.emptyStream();114 } else if ("java.util.stream.DoubleStream".equals(type.getName())) {115 return JavaEightUtil.emptyDoubleStream();116 } else if ("java.util.stream.IntStream".equals(type.getName())) {117 return JavaEightUtil.emptyIntStream();118 } else if ("java.util.stream.LongStream".equals(type.getName())) {119 return JavaEightUtil.emptyLongStream();120 }121 //Let's not care about the rest of collections.122 return null;123 }124}...
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2public class JavaEightUtilExample {3 public static void main(String[] args) {4 JavaEightUtil javaEightUtil = new JavaEightUtil();5 System.out.println("isJavaEightAvailable(): " + javaEightUtil.isJavaEightAvailable());6 }7}8isJavaEightAvailable(): false
JavaEightUtil
Using AI Code Generation
1package org.mockito.internal.util;2import java.util.function.Supplier;3public class JavaEightUtil {4 public static <T> Supplier<T> toSupplier(T value) {5 return new Supplier<T>() {6 public T get() {7 return value;8 }9 };10 }11}12package org.mockito.internal.util;13import java.util.function.Supplier;14public class JavaEightUtil {15 public static <T> Supplier<T> toSupplier(T value) {16 return () -> value;17 }18}19package org.mockito.internal.util;20import java.util.function.Supplier;21public class JavaEightUtil {22 public static <T> Supplier<T> toSupplier(T value) {23 return () -> {24 return value;25 };26 }27}28package org.mockito.internal.util;29import java.util.function.Supplier;30public class JavaEightUtil {31 public static <T> Supplier<T> toSupplier(T value) {32 return () -> {33 return value;34 };35 }36}37package org.mockito.internal.util;38import java.util.function.Supplier;39public class JavaEightUtil {40 public static <T> Supplier<T> toSupplier(T value) {41 return () -> {42 return value;43 };44 }45}46package org.mockito.internal.util;47import java.util.function.Supplier;48public class JavaEightUtil {49 public static <T> Supplier<T> toSupplier(T value) {50 return () -> {51 return value;52 };53 }54}55package org.mockito.internal.util;56import java.util.function.Supplier;57public class JavaEightUtil {58 public static <T> Supplier<T> toSupplier(T value) {59 return () -> {60 return value;61 };62 }63}64package org.mockito.internal.util;65import java.util.function.Supplier;66public class JavaEightUtil {67 public static <T> Supplier<T> toSupplier(T value) {68 return () -> {69 return value;70 };71 }72}73package org.mockito.internal.util;74import java.util.function.Supplier;75public class JavaEightUtil {76 public static <T> Supplier<T> toSupplier(T value) {77 return () -> {78 return value;79 };80 }81}
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2public class JavaEightUtilDemo {3 public static void main(String[] args) {4 JavaEightUtil javaEightUtil = new JavaEightUtil();5 System.out.println("javaEightUtil.isJavaEightOrHigher() = " + javaEightUtil.isJavaEightOrHigher());6 }7}8javaEightUtil.isJavaEightOrHigher() = true
JavaEightUtil
Using AI Code Generation
1public class JavaEightUtil {2 public static boolean isJavaEightOrHigher() {3 return true;4 }5}6public class JavaEightUtil {7 public static boolean isJavaEightOrHigher() {8 return false;9 }10}11public class JavaEightUtil {12 public static boolean isJavaEightOrHigher() {13 return true;14 }15}16public class JavaEightUtil {17 public static boolean isJavaEightOrHigher() {18 return false;19 }20}21public class JavaEightUtil {22 public static boolean isJavaEightOrHigher() {23 return true;24 }25}26public class JavaEightUtil {27 public static boolean isJavaEightOrHigher() {28 return false;29 }30}
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2public class Example {3 public static void main(String[] args) {4 System.out.println("isJavaEightOrHigher() = " + JavaEightUtil.isJavaEightOrHigher());5 }6}7isJavaEightOrHigher() = true8isJavaEightOrHigher() = false
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2public class Test {3 public static void main(String[] args) {4 JavaEightUtil.isJava8OrHigher();5 }6}
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2public class one {3 public static void main(String[] args) {4 boolean result = JavaEightUtil.isJavaEightOrHigher();5 System.out.println(result);6 }7}
JavaEightUtil
Using AI Code Generation
1import org.mockito.internal.util.JavaEightUtil;2import java.util.Optional;3class Test{4 public static void main(String args[]){5 Optional<String> optional=Optional.of("java");6 System.out.println(JavaEightUtil.toStream(optional).count());7 }8}9Recommended Posts: Java Stream count() Method10Java Stream allMatch() Method11Java Stream anyMatch() Method12Java Stream noneMatch() Method13Java Stream findFirst() Method14Java Stream findAny() Method15Java Stream min() Method16Java Stream max() Method17Java Stream forEach() Method18Java Stream reduce() Method19Java Stream collect() Method20Java Stream toArray() Method21Java Stream toList() Method22Java Stream toSet() Method23Java Stream toMap() Method24Java Stream average() Method25Java Stream map() Method26Java Stream filter() Method27Java Stream flatMap() Method28Java Stream sorted() Method29Java Stream distinct() Method30Java Stream skip() Method31Java Stream limit() Method32Java Stream of() Method33Java Stream empty() Method34Java Stream iterate() Method35Java Stream generate() Method36Java Stream concat() Method37Java Stream.Builder add() Method38Java Stream.Builder build() Method39Java Stream.Builder accept() Method40Java Stream.Builder of() Method41Java Stream.Builder ofNullable() Method42Java Stream.Builder empty() Method43Java Stream.Builder iterate() Method44Java Stream.Builder generate() Method45Java Stream.Builder concat() Method46Java Stream.Builder add() Method47Java Stream.Builder build() Method48Java Stream.Builder accept() Method49Java Stream.Builder of() Method50Java Stream.Builder ofNullable() Method51Java Stream.Builder empty() Method52Java Stream.Builder iterate() Method53Java Stream.Builder generate() Method54Java Stream.Builder concat() Method55Java Stream.Builder add() Method56Java Stream.Builder build() Method57Java Stream.Builder accept() Method58Java Stream.Builder of() Method59Java Stream.Builder ofNullable() Method60Java Stream.Builder empty() Method61Java Stream.Builder iterate() Method62Java Stream.Builder generate() Method63Java Stream.Builder concat() Method64Java Stream.Builder add() Method65Java Stream.Builder build() Method66Java Stream.Builder accept() Method67Java Stream.Builder of() Method68Java Stream.Builder ofNullable() Method69Java Stream.Builder empty() Method70Java Stream.Builder iterate() Method71Java Stream.Builder generate() Method
What's the point of verifying the number of times a function is called with Mockito?
What's the difference between Mockito Matchers isA, any, eq, and same?
How to mock a void return method affecting an object
Mocking a Spring Validator when unit testing Controller
Mockito. Verify method arguments
Kotlin Mockito always return object passed as an argument
How to mock an enum singleton class using Mockito/Powermock?
Spring 3.2 Test, com.jajway not included as dependency
Mockito match any class argument
Test class with a new() call in it with Mockito
The need is simple: to verify that the correct number of invocations were made. There are scenarios in which method calls should not happen, and others in which they should happen more or less than the default.
Consider the following modified version of embarkOnQuest
:
public void embarkOnQuest() {
quest.embark();
quest.embarkAgain();
}
And suppose you are testing error cases for quest.embark()
:
@Test
public void knightShouldEmbarkOnQuest() {
Quest mockQuest = mock(Quest.class);
Mockito.doThrow(RuntimeException.class).when(mockQuest).embark();
...
}
In this case you want to make sure that quest.embarkAgain
is NOT invoked (or is invoked 0 times):
verify(mockQuest, times(0)).embarkAgain(); //or verifyZeroInteractions
Of course this is one other simple example. There are many other examples that could be added:
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
In today’s fast-paced world, the primary goal of every business is to release their application or websites to the end users as early as possible. As a result, businesses constantly search for ways to test, measure, and improve their products. With the increase in competition, faster time to market (TTM) has become vital for any business to survive in today’s market. However, one of the possible challenges many business teams face is the release cycle time, which usually gets extended for several reasons.
As everyone knows, the mobile industry has taken over the world and is the fastest emerging industry in terms of technology and business. It is possible to do all the tasks using a mobile phone, for which earlier we had to use a computer. According to Statista, in 2021, smartphone vendors sold around 1.43 billion smartphones worldwide. The smartphone penetration rate has been continuously rising, reaching 78.05 percent in 2020. By 2025, it is expected that almost 87 percent of all mobile users in the United States will own a smartphone.
Even though several frameworks are available in the market for automation testing, Selenium is one of the most renowned open-source frameworks used by experts due to its numerous features and benefits.
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!!