Best Mockito code snippet using org.mockito.internal.matchers.NotNull
Source:AnalyticsUnitTest.java
1package bf.io.openshop;2import android.content.Context;3import android.os.Bundle;4import com.facebook.appevents.AppEventsLogger;5import com.google.android.gms.analytics.GoogleAnalytics;6import com.google.android.gms.analytics.Tracker;7import org.junit.Before;8import org.junit.Test;9import org.junit.runner.RunWith;10import org.mockito.Mock;11import org.mockito.MockitoAnnotations;12import org.powermock.api.mockito.PowerMockito;13import org.powermock.core.classloader.annotations.PrepareForTest;14import org.powermock.modules.junit4.PowerMockRunner;15import org.powermock.reflect.Whitebox;16import java.util.ArrayList;17import java.util.HashMap;18import java.util.List;19import java.util.Map;20import bf.io.openshop.entities.Shop;21import bf.io.openshop.entities.cart.Cart;22import bf.io.openshop.entities.cart.CartProductItem;23import bf.io.openshop.entities.cart.CartProductItemVariant;24import bf.io.openshop.entities.delivery.Shipping;25import bf.io.openshop.utils.Analytics;26import static org.junit.Assert.assertEquals;27import static org.junit.Assert.assertNotEquals;28import static org.mockito.Matchers.any;29import static org.mockito.Matchers.anyDouble;30import static org.mockito.Matchers.anyMap;31import static org.mockito.Matchers.anyObject;32import static org.mockito.Matchers.notNull;33import static org.mockito.Mockito.never;34import static org.mockito.Mockito.times;35import static org.mockito.Mockito.verify;36import static org.mockito.Mockito.verifyNoMoreInteractions;37import static org.powermock.api.mockito.PowerMockito.doNothing;38import static org.powermock.api.mockito.PowerMockito.doReturn;39import static org.powermock.api.mockito.PowerMockito.verifyPrivate;40import static org.powermock.api.mockito.PowerMockito.verifyStatic;41import static org.powermock.api.mockito.PowerMockito.when;42/**43 * Simple unit tests for {@link Analytics} class.44 * <p/>45 * Careful: Because it is testing static class with static methods and static fields.46 */47@RunWith(PowerMockRunner.class)48@PrepareForTest({Analytics.class, GoogleAnalytics.class, AppEventsLogger.class, SettingsMy.class})49public class AnalyticsUnitTest {50 @Mock51 private Context mockContext;52 @Mock53 private GoogleAnalytics mockAnalytics;54 @Mock55 private Tracker mockTracker;56 @Mock57 private Tracker mockTrackerApp;58 @Mock59 private AppEventsLogger mockAppEventsLogger;60 private Shop testShop = new Shop("testShop", "UA-test");61 @Before62 public void preparation() {63 // clean up64 MockitoAnnotations.initMocks(this); // for case them used another runner65 PowerMockito.spy(Analytics.class);66 Whitebox.setInternalState(Analytics.class, "mTrackers", new HashMap<>());67 Whitebox.setInternalState(Analytics.class, "facebookLogger", (Object[]) null);68 Whitebox.setInternalState(Analytics.class, "campaignUri", (Object[]) null);69 }70 private void prepareMockedFields() throws Exception {71 // Mock responses72 PowerMockito.mockStatic(GoogleAnalytics.class);73 PowerMockito.mockStatic(AppEventsLogger.class);74 doReturn(mockAnalytics).when(GoogleAnalytics.class, "getInstance", mockContext);75 doReturn(mockAppEventsLogger).when(AppEventsLogger.class, "newLogger", anyObject());76 when(mockAnalytics.newTracker(R.xml.global_tracker)).thenReturn(mockTracker);77 when(mockAnalytics.newTracker(testShop.getGoogleUa())).thenReturn(mockTrackerApp);78 }79 @Test80 public void prepareGlobalTrackerAndFbLoggerTest() throws Exception {81 // Mock responses82 PowerMockito.mockStatic(GoogleAnalytics.class);83 PowerMockito.mockStatic(AppEventsLogger.class);84 doReturn(mockAnalytics).when(GoogleAnalytics.class, "getInstance", mockContext);85 doReturn(mockAppEventsLogger).when(AppEventsLogger.class, "newLogger", anyObject());86 when(mockAnalytics.newTracker(R.xml.global_tracker)).thenReturn(mockTracker);87 // Tested method invocation88 Analytics.prepareTrackersAndFbLogger(null, mockContext);89 // Verify results90 verifyStatic(times(1));91 GoogleAnalytics.getInstance(mockContext);92 verifyStatic(times(1));93 Analytics.deleteAppTrackers();94 verify(mockAnalytics, times(1)).newTracker(R.xml.global_tracker);95 verify(mockTracker, times(1)).enableAutoActivityTracking(true);96 verify(mockTracker, times(1)).enableExceptionReporting(true);97 verify(mockTracker, times(1)).enableAdvertisingIdCollection(true);98 verifyNoMoreInteractions(mockTracker);99 HashMap<String, Tracker> trackersField = Whitebox.getInternalState(Analytics.class, "mTrackers");100 assertEquals(trackersField.size(), 1);101 AppEventsLogger appEventsLoggerField = Whitebox.getInternalState(Analytics.class, "facebookLogger");102 assertNotEquals(appEventsLoggerField, null);103 }104 @Test105 public void prepareTrackersAndFbLoggerTest() throws Exception {106 prepareMockedFields();107 // Tested method invocation108 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);109 // Verify results110 verifyStatic(times(1));111 GoogleAnalytics.getInstance(mockContext);112 verifyStatic(never());113 Analytics.deleteAppTrackers();114 verify(mockAnalytics, times(1)).newTracker(testShop.getGoogleUa());115 verify(mockAnalytics, times(1)).newTracker(R.xml.global_tracker);116 verify(mockTrackerApp, times(1)).enableAutoActivityTracking(true);117 verify(mockTrackerApp, times(1)).enableExceptionReporting(false);118 verify(mockTrackerApp, times(1)).enableAdvertisingIdCollection(true);119 verifyNoMoreInteractions(mockTrackerApp);120 verify(mockTracker, times(1)).enableAutoActivityTracking(true);121 verify(mockTracker, times(1)).enableExceptionReporting(true);122 verify(mockTracker, times(1)).enableAdvertisingIdCollection(true);123 verifyNoMoreInteractions(mockTracker);124 HashMap<String, Tracker> trackersField = Whitebox.getInternalState(Analytics.class, "mTrackers");125 assertEquals(trackersField.size(), 2);126 AppEventsLogger appEventsLoggerField = Whitebox.getInternalState(Analytics.class, "facebookLogger");127 assertNotEquals(appEventsLoggerField, null);128 }129 @Test130 public void deleteAppTrackersTest() throws Exception {131 prepareMockedFields();132 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);133 // Check size before deletion134 HashMap<String, Tracker> trackersField = Whitebox.getInternalState(Analytics.class, "mTrackers");135 assertEquals(trackersField.size(), 2);136 // Tested method invocation137 Analytics.deleteAppTrackers();138 // Verify final size139 trackersField = Whitebox.getInternalState(Analytics.class, "mTrackers");140 assertEquals(trackersField.size(), 1);141 }142 @Test143 public void setCampaignUriStringTest() throws Exception {144 String testCampaignUri = "www.site.com&utm_medium=email&utm_source=Newsletter";145 doNothing().when(Analytics.class, "sendCampaignInfo");146 // Check before set147 String campaignUriField = Whitebox.getInternalState(Analytics.class, "campaignUri");148 assertEquals(campaignUriField, null);149 Analytics.setCampaignUriString(testCampaignUri);150 verifyPrivate(Analytics.class, never()).invoke("sendCampaignInfo");151 campaignUriField = Whitebox.getInternalState(Analytics.class, "campaignUri");152 assertEquals(campaignUriField, testCampaignUri);153 }154 @Test155 public void setCampaignUriStringTest2() throws Exception {156 prepareMockedFields();157 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);158 String testCampaignUri = "www.site.com&utm_medium=email&utm_source=Newsletter";159 // Check before set160 String campaignUriField = Whitebox.getInternalState(Analytics.class, "campaignUri");161 assertEquals(campaignUriField, null);162 Analytics.setCampaignUriString(testCampaignUri);163 // Verify values164 campaignUriField = Whitebox.getInternalState(Analytics.class, "campaignUri");165 assertEquals(campaignUriField, testCampaignUri);166 verifyPrivate(Analytics.class, times(2)).invoke("sendCampaignInfo");167 // Verify corresponding tracker calls168 verify(mockTracker, times(1)).send(anyMap());169 verify(mockTrackerApp, times(1)).send(anyMap());170 }171 @Test172 public void logProductViewTest() throws Exception {173 prepareMockedFields();174 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);175 long testRemoteId = 123456;176 String testName = "test product";177 Analytics.logProductView(testRemoteId, testName);178 verify(mockAppEventsLogger, times(1)).logEvent((String) notNull(), (Bundle) notNull());179 verify(mockTracker, times(1)).send((Map<String, String>) notNull());180 verify(mockTrackerApp, times(1)).send((Map<String, String>) notNull());181 }182 @Test183 public void logAddProductToCartTest() throws Exception {184 prepareMockedFields();185 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);186 long testRemoteId = 123456;187 String testName = "test product";188 double testDiscountPrice = 52.35;189 Analytics.logAddProductToCart(testRemoteId, testName, testDiscountPrice);190 verify(mockAppEventsLogger, times(1)).logEvent((String) notNull(), anyDouble(), (Bundle) notNull());191 verify(mockTracker, times(1)).send((Map<String, String>) notNull());192 verify(mockTrackerApp, times(1)).send((Map<String, String>) notNull());193 }194 @Test195 public void logShopChangeTest() throws Exception {196 prepareMockedFields();197 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);198 Shop testShop1 = new Shop("shop1", null);199 Shop testShop2 = new Shop("shop2", null);200 Analytics.logShopChange(testShop1, testShop2);201 verify(mockAppEventsLogger, times(1)).logEvent((String) notNull(), (Bundle) notNull());202 verify(mockTracker, times(1)).send((Map<String, String>) notNull());203 verify(mockTrackerApp, times(1)).send((Map<String, String>) notNull());204 }205 @Test206 public void logOpenedByNotificationTest() throws Exception {207 prepareMockedFields();208 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);209 Analytics.logOpenedByNotification("testContent");210 PowerMockito.verifyNoMoreInteractions(mockAppEventsLogger);211 verify(mockTracker, times(1)).send((Map<String, String>) notNull());212 verify(mockTrackerApp, times(1)).send((Map<String, String>) notNull());213 }214 @Test215 public void logCategoryViewBadFormatTest() throws Exception {216 prepareMockedFields();217 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);218 String testName = "test product";219 Analytics.logCategoryView(0, testName, false);220 PowerMockito.verifyNoMoreInteractions(mockAppEventsLogger);221 verify(mockTracker, never()).send((Map<String, String>) notNull());222 verify(mockTrackerApp, never()).send((Map<String, String>) notNull());223 }224 @Test225 public void logCategoryViewOkTest() throws Exception {226 prepareMockedFields();227 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);228 String testName = "test product";229 Analytics.logCategoryView(123, testName, false);230 verify(mockAppEventsLogger, times(1)).logEvent((String) notNull(), (Bundle) notNull());231 verify(mockTracker, times(1)).send((Map<String, String>) notNull());232 verify(mockTrackerApp, times(1)).send((Map<String, String>) notNull());233 }234 @Test235 public void logOrderCreatedEventTest() throws Exception {236 prepareMockedFields();237 Analytics.prepareTrackersAndFbLogger(testShop, mockContext);238 PowerMockito.mockStatic(SettingsMy.class);239 doReturn(testShop).when(SettingsMy.class, "getActualNonNullShop", any());240 // Prepare data241 Shipping testShipping = new Shipping();242 testShipping.setPrice(100);243 Cart testCart = new Cart();244 testCart.setCurrency("EUR");245 List<CartProductItem> testCartProductItems = new ArrayList<>();246 CartProductItem cartProductItem1 = new CartProductItem();247 cartProductItem1.setId(111);248 cartProductItem1.setQuantity(2);249 CartProductItemVariant cartProductItemVariant1 = new CartProductItemVariant();250 cartProductItemVariant1.setName("variant1");251 cartProductItemVariant1.setPrice(100);252 cartProductItemVariant1.setDiscountPrice(50);253 cartProductItemVariant1.setRemoteId(1111);254 cartProductItemVariant1.setCategory(11);255 cartProductItem1.setVariant(cartProductItemVariant1);256 testCartProductItems.add(cartProductItem1);257 CartProductItem cartProductItem2 = new CartProductItem();258 cartProductItem2.setId(112);259 cartProductItem2.setQuantity(2);260 CartProductItemVariant cartProductItemVariant2 = new CartProductItemVariant();261 cartProductItemVariant2.setName("variant2");262 cartProductItemVariant2.setPrice(150);263 cartProductItemVariant2.setDiscountPrice(0);264 cartProductItemVariant2.setRemoteId(1122);265 cartProductItemVariant2.setCategory(11);266 cartProductItem2.setVariant(cartProductItemVariant2);267 testCartProductItems.add(cartProductItem2);268 testCart.setItems(testCartProductItems);269 // Execute270 Analytics.logOrderCreatedEvent(testCart, "123456", (double) 500, testShipping);271 // Verify272 verify(mockAppEventsLogger, times(4)).logEvent((String) notNull(), anyDouble(), (Bundle) notNull());273 verify(mockTracker, times(4)).send((Map<String, String>) notNull());274 verify(mockTrackerApp, times(4)).send((Map<String, String>) notNull());275 }276}...
Source:ArgumentMatchers.java
...14import org.mockito.internal.matchers.EndsWith;15import org.mockito.internal.matchers.Equals;16import org.mockito.internal.matchers.InstanceOf;17import org.mockito.internal.matchers.Matches;18import org.mockito.internal.matchers.NotNull;19import org.mockito.internal.matchers.Null;20import org.mockito.internal.matchers.Same;21import org.mockito.internal.matchers.StartsWith;22import org.mockito.internal.matchers.apachecommons.ReflectionEquals;23import org.mockito.internal.progress.ThreadSafeMockingProgress;24import org.mockito.internal.util.Primitives;25public class ArgumentMatchers {26 public static <T> T any() {27 return anyObject();28 }29 @Deprecated30 public static <T> T anyObject() {31 reportMatcher(Any.ANY);32 return null;33 }34 public static <T> T any(Class<T> cls) {35 reportMatcher(new InstanceOf.VarArgAware(cls, "<any " + cls.getCanonicalName() + HtmlObject.HtmlMarkUp.CLOSE_BRACKER));36 return Primitives.defaultValue(cls);37 }38 public static <T> T isA(Class<T> cls) {39 reportMatcher(new InstanceOf(cls));40 return Primitives.defaultValue(cls);41 }42 @Deprecated43 public static <T> T anyVararg() {44 any();45 return null;46 }47 public static boolean anyBoolean() {48 reportMatcher(new InstanceOf(Boolean.class, "<any boolean>"));49 return false;50 }51 public static byte anyByte() {52 reportMatcher(new InstanceOf(Byte.class, "<any byte>"));53 return 0;54 }55 public static char anyChar() {56 reportMatcher(new InstanceOf(Character.class, "<any char>"));57 return 0;58 }59 public static int anyInt() {60 reportMatcher(new InstanceOf(Integer.class, "<any integer>"));61 return 0;62 }63 public static long anyLong() {64 reportMatcher(new InstanceOf(Long.class, "<any long>"));65 return 0;66 }67 public static float anyFloat() {68 reportMatcher(new InstanceOf(Float.class, "<any float>"));69 return 0.0f;70 }71 public static double anyDouble() {72 reportMatcher(new InstanceOf(Double.class, "<any double>"));73 return FirebaseRemoteConfig.DEFAULT_VALUE_FOR_DOUBLE;74 }75 public static short anyShort() {76 reportMatcher(new InstanceOf(Short.class, "<any short>"));77 return 0;78 }79 public static String anyString() {80 reportMatcher(new InstanceOf(String.class, "<any string>"));81 return "";82 }83 public static <T> List<T> anyList() {84 reportMatcher(new InstanceOf(List.class, "<any List>"));85 return new ArrayList(0);86 }87 @Deprecated88 public static <T> List<T> anyListOf(Class<T> cls) {89 return anyList();90 }91 public static <T> Set<T> anySet() {92 reportMatcher(new InstanceOf(Set.class, "<any set>"));93 return new HashSet(0);94 }95 @Deprecated96 public static <T> Set<T> anySetOf(Class<T> cls) {97 return anySet();98 }99 public static <K, V> Map<K, V> anyMap() {100 reportMatcher(new InstanceOf(Map.class, "<any map>"));101 return new HashMap(0);102 }103 @Deprecated104 public static <K, V> Map<K, V> anyMapOf(Class<K> cls, Class<V> cls2) {105 return anyMap();106 }107 public static <T> Collection<T> anyCollection() {108 reportMatcher(new InstanceOf(Collection.class, "<any collection>"));109 return new ArrayList(0);110 }111 @Deprecated112 public static <T> Collection<T> anyCollectionOf(Class<T> cls) {113 return anyCollection();114 }115 public static <T> Iterable<T> anyIterable() {116 reportMatcher(new InstanceOf(Iterable.class, "<any iterable>"));117 return new ArrayList(0);118 }119 @Deprecated120 public static <T> Iterable<T> anyIterableOf(Class<T> cls) {121 return anyIterable();122 }123 public static boolean eq(boolean z) {124 reportMatcher(new Equals(Boolean.valueOf(z)));125 return false;126 }127 public static byte eq(byte b) {128 reportMatcher(new Equals(Byte.valueOf(b)));129 return 0;130 }131 public static char eq(char c) {132 reportMatcher(new Equals(Character.valueOf(c)));133 return 0;134 }135 public static double eq(double d) {136 reportMatcher(new Equals(Double.valueOf(d)));137 return FirebaseRemoteConfig.DEFAULT_VALUE_FOR_DOUBLE;138 }139 public static float eq(float f) {140 reportMatcher(new Equals(Float.valueOf(f)));141 return 0.0f;142 }143 public static int eq(int i) {144 reportMatcher(new Equals(Integer.valueOf(i)));145 return 0;146 }147 public static long eq(long j) {148 reportMatcher(new Equals(Long.valueOf(j)));149 return 0;150 }151 public static short eq(short s) {152 reportMatcher(new Equals(Short.valueOf(s)));153 return 0;154 }155 public static <T> T eq(T t) {156 reportMatcher(new Equals(t));157 if (t == null) {158 return null;159 }160 return Primitives.defaultValue(t.getClass());161 }162 public static <T> T refEq(T t, String... strArr) {163 reportMatcher(new ReflectionEquals(t, strArr));164 return null;165 }166 public static <T> T same(T t) {167 reportMatcher(new Same(t));168 if (t == null) {169 return null;170 }171 return Primitives.defaultValue(t.getClass());172 }173 public static <T> T isNull() {174 reportMatcher(Null.NULL);175 return null;176 }177 @Deprecated178 public static <T> T isNull(Class<T> cls) {179 return isNull();180 }181 public static <T> T notNull() {182 reportMatcher(NotNull.NOT_NULL);183 return null;184 }185 @Deprecated186 public static <T> T notNull(Class<T> cls) {187 return notNull();188 }189 public static <T> T isNotNull() {190 return notNull();191 }192 @Deprecated193 public static <T> T isNotNull(Class<T> cls) {194 return notNull(cls);195 }196 public static <T> T nullable(Class<T> cls) {197 AdditionalMatchers.or(isNull(), isA(cls));198 return Primitives.defaultValue(cls);199 }200 public static String contains(String str) {201 reportMatcher(new Contains(str));202 return "";203 }204 public static String matches(String str) {205 reportMatcher(new Matches(str));206 return "";207 }...
Source:MatchersToStringTest.java
...13import org.mockito.internal.matchers.Equals;14import org.mockito.internal.matchers.Find;15import org.mockito.internal.matchers.Matches;16import org.mockito.internal.matchers.Not;17import org.mockito.internal.matchers.NotNull;18import org.mockito.internal.matchers.Null;19import org.mockito.internal.matchers.Or;20import org.mockito.internal.matchers.Same;21import org.mockito.internal.matchers.StartsWith;22import org.mockito.test.mockitoutil.TestBase;23import static org.junit.Assert.assertEquals;24public class MatchersToStringTest extends TestBase {25 @Test26 public void sameToStringWithString() {27 assertEquals("same(\"X\")", new Same("X").toString());28 }29 @Test30 public void nullToString() {31 assertEquals("isNull()", Null.NULL.toString());32 }33 @Test34 public void notNullToString() {35 assertEquals("notNull()", NotNull.NOT_NULL.toString());36 }37 @Test38 public void anyToString() {39 assertEquals("<any>", Any.ANY.toString());40 }41 @Test42 public void sameToStringWithChar() {43 assertEquals("same('x')", new Same('x').toString());44 }45 @Test46 public void sameToStringWithObject() {47 Object o = new Object() {48 @Override49 public String toString() {...
NotNull
Using AI Code Generation
1package org.mockito.internal.matchers;2import org.mockito.ArgumentMatcher;3public class NotNull<T> extends ArgumentMatcher<T> {4 public boolean matches(Object o) {5 return o != null;6 }7 public String toString() {8 return "notNull()";9 }10}11package org.mockito.internal.matchers;12public class NotNull<T> extends ArgumentMatcher<T> {13 public boolean matches(Object o) {14 return o != null;15 }16 public String toString() {17 return "notNull()";18 }19}20package org.mockito.internal.matchers;21public class NotNull<T> extends ArgumentMatcher<T> {22 public boolean matches(Object o) {23 return o != null;24 }25 public String toString() {26 return "notNull()";27 }28}29package org.mockito.internal.matchers;30public class NotNull<T> extends ArgumentMatcher<T> {31 public boolean matches(Object o) {32 return o != null;33 }34 public String toString() {35 return "notNull()";36 }37}38package org.mockito.internal.matchers;39public class NotNull<T> extends ArgumentMatcher<T> {40 public boolean matches(Object o) {41 return o != null;42 }43 public String toString() {44 return "notNull()";45 }46}47package org.mockito.internal.matchers;48public class NotNull<T> extends ArgumentMatcher<T> {49 public boolean matches(Object o) {50 return o != null;51 }52 public String toString() {53 return "notNull()";54 }55}56package org.mockito.internal.matchers;57public class NotNull<T> extends ArgumentMatcher<T> {58 public boolean matches(Object o) {59 return o != null;60 }61 public String toString() {62 return "notNull()";63 }64}65package org.mockito.internal.matchers;66public class NotNull<T> extends ArgumentMatcher<T> {67 public boolean matches(Object o) {68 return o != null;69 }70 public String toString() {71 return "notNull()";72 }73}74package org.mockito.internal.matchers;75public class NotNull<T> extends ArgumentMatcher<T> {76 public boolean matches(Object o) {77 return o != null;78 }79 public String toString() {80 return "notNull()";81 }82}83package org.mockito.internal.matchers;84public class NotNull<T> extends ArgumentMatcher<T> {85 public boolean matches(Object o) {86 return o != null;
NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.mockito.ArgumentMatcher;3import org.mockito.Matchers;4import org.mockito.Mock;5import org.mockito.Mockito;6import org.mockito.MockitoAnnotations;7import org.mockito.Spy;8import org.mockito.invocation.InvocationOnMock;9import org.mockito.stubbing.Answer;10import org.testng.Assert;11import org.testng.annotations.BeforeMethod;12import org.testng.annotations.Test;13import java.util.ArrayList;14import java.util.List;15import java.util.concurrent.Callable;16import java.util.concurrent.Future;17import java.util.concurrent.FutureTask;18import static org.mockito.Matchers.any;19import static org.mockito.Matchers.anyInt;20import static org.mockito.Matchers.anyString;21import static org.mockito.Matchers.argThat;22import static org.mockito.Matchers.eq;23import static org.mockito.Mockito.doAnswer;24import static org.mockito.Mockito.doCallRealMethod;25import static org.mockito.Mockito.doNothing;26import static org.mockito.Mockito.doReturn;27import static org.mockito.Mockito.doThrow;28import static org.mockito.Mockito.mock;29import static org.mockito.Mockito.times;30import static org.mockito.Mockito.verify;31import static org.mockito.Mockito.when;32public class MockitoTest {33 private List<String> mockList;34 private List<String> spyList = new ArrayList<String>();35 public void setUp() {36 MockitoAnnotations.initMocks(this);37 }38 public void testMock() {39 mockList.add("one");40 Mockito.verify(mockList).add("one");41 Assert.assertEquals(0, mockList.size());42 }43 public void testSpy() {44 spyList.add("one");45 spyList.add("two");46 Mockito.verify(spyList).add("one");47 Mockito.verify(spyList).add("two");48 Assert.assertEquals(2, spyList.size());49 Assert.assertEquals("one", spyList.get(0));50 Assert.assertEquals("two", spyList.get(1));51 }52 public void testStub() {53 List mockList = mock(List.class);54 when(mockList.get(0)).thenReturn("first");55 when(mockList.get(1)).thenThrow(new RuntimeException());56 Assert.assertEquals("first", mockList.get(0));57 Assert.assertEquals(null, mockList.get(999));58 try {59 mockList.get(1);60 } catch (Exception e) {61 Assert.assertTrue(e instanceof RuntimeException);62 }63 }
NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.mockito.ArgumentMatcher;3import static org.mockito.Matchers.argThat;4import static org.mockito.Matchers.any;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.when;7import static org.mockito.Mockito.verify;8import static org.mockito.Mockito.times;9import static org.mockito.Mockito.doThrow;10import static org.mockito.Mockito.doAnswer;11import static org.mockito.Mockito.spy;12import static org.mockito.Mockito.doNothing;13import static org.mockito.Mockito.doReturn;14import static org.mockito.Mockito.doCallRealMethod;15{16 public void m1(int x)17 {18 System.out.println("m1() of A class");19 }20}21{22 public static void main(String[] args)23 {24 A a = mock(A.class);25 a.m1(any(int.class));26 verify(a).m1(any(int.class));27 }28}29Output: m1() of A class30How to use any() matcher with primitive types?31For primitive types, we can use anyInt(), anyDouble(), anyByte() etc. methods of Mockito class. See the example below:32import org.mockito.ArgumentMatcher;33import static org.mockito.Matchers.argThat;34import static org.mockito.Matchers.any;35import static org.mockito.Mockito.mock;36import static org.mockito.Mockito.when;37import static org.mockito.Mockito.verify;38import static org.mockito.Mockito.times;39import static org.mockito.Mockito.doThrow;40import static org.mockito.Mockito.doAnswer;41import static org.mockito.Mockito.spy;42import static org.mockito.Mockito.doNothing;43import static org.mockito.Mockito.doReturn;44import static org.mockito.Mockito.doCallRealMethod;45{46 public void m1(int x)47 {48 System.out.println("m1() of A class");49 }50}51{52 public static void main(String[] args)53 {54 A a = mock(A.class);55 a.m1(anyInt());56 verify(a).m1(anyInt());57 }58}59Output: m1() of A class60How to use any() matcher with Object types?61For object types, we can use anyObject() method of Mockito class. See the example below:62import org.mockito.ArgumentMatcher;63import static org.mockito.Matchers.argThat;64import static org.mockito.Matchers.any;65import
NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.mockito.ArgumentMatcher;3import org.mockito.Mock;4import org.mockito.MockitoAnnotations;5import org.mockito.InjectMocks;6import org.mockito.runners.MockitoJUnitRunner;7import org.junit.runner.RunWith;8import org.junit.Before;9import org.junit.Test;10import static org.mockito.Matchers.*;11import static org.junit.Assert.*;12import static org.mockito.Mockito.*;13@RunWith(MockitoJUnitRunner.class)14public class Test1 {15 private List<String> list;16 private List<String> list2 = new ArrayList<String>();17 public void setUp() {18 MockitoAnnotations.initMocks(this);19 }20 public void test1() {21 when(list.get(anyInt())).thenReturn("a");22 assertEquals("a", list.get(1));23 assertEquals("a", list.get(2));24 }25 public void test2() {26 when(list.get(anyInt())).thenReturn("a");27 assertEquals("a", list.get(1));28 assertEquals("a", list.get(2));29 }30}31import org.mockito.internal.matchers.NotNull;32import org.mockito.ArgumentMatcher;33import org.mockito.Mock;34import org.mockito.MockitoAnnotations;35import org.mockito.InjectMocks;36import org.mockito.runners.MockitoJUnitRunner;37import org.junit.runner.RunWith;38import org.junit.Before;39import org.junit.Test;40import static org.mockito.Matchers.*;41import static org.junit.Assert.*;42import static org.mockito.Mockito.*;43@RunWith(MockitoJUnitRunner.class)44public class Test2 {45 private List<String> list;46 private List<String> list2 = new ArrayList<String>();47 public void setUp() {48 MockitoAnnotations.initMocks(this);49 }50 public void test1() {51 when(list.get(anyInt())).thenReturn("a");52 assertEquals("a", list.get(1));53 assertEquals("a", list.get(2));54 }55 public void test2() {56 when(list.get(anyInt())).thenReturn("a");57 assertEquals("a", list.get(1));58 assertEquals("a", list.get(2));59 }60}
NotNull
Using AI Code Generation
1package com.example;2import org.mockito.internal.matchers.NotNull;3public class Example {4 public static void main(String[] args) {5 NotNull notNull = new NotNull();6 System.out.println(notNull.matches(null));7 }8}
NotNull
Using AI Code Generation
1package com.example;2import org.mockito.internal.matchers.NotNull;3public class TestNotNull {4 public static void main(String[] args) {5 NotNull notNull = new NotNull();6 System.out.println(notNull.matches("hello"));7 System.out.println(notNull.matches(null));8 }9}
NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import static org.mockito.Mockito.*;3import static org.mockito.Matchers.*;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.when;6public class MockitoTest {7 public void testNotNull() {8 List mockedList = mock(List.class);9 mockedList.add(new NotNull());10 verify(mockedList).add(new NotNull());11 }12}13BUILD SUCCESSFUL (total time: 0 seconds)
NotNull
Using AI Code Generation
1public void test(){2 NotNull notNull = new NotNull();3 assertNotNull(notNull);4}5public void test(){6 NotNull notNull = new NotNull();7 assertNotNull(notNull);8}9public void test(){10 NotNull notNull = new NotNull();11 assertNotNull(notNull);12}13public void test(){14 NotNull notNull = new NotNull();15 assertNotNull(notNull);16}17public void test(){18 NotNull notNull = new NotNull();19 assertNotNull(notNull);20}21public void test(){22 NotNull notNull = new NotNull();23 assertNotNull(notNull);24}25public void test(){26 NotNull notNull = new NotNull();27 assertNotNull(notNull);28}29public void test(){30 NotNull notNull = new NotNull();31 assertNotNull(notNull);32}33public void test(){34 NotNull notNull = new NotNull();35 assertNotNull(notNull);36}37public void test(){
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!!