Best Mockito code snippet using org.mockito.internal.matchers.NotNull.NotNull
Source:ProfileMigratableTest.java  
1/**2 * Copyright (c) Codice Foundation3 *4 * <p>This is free software: you can redistribute it and/or modify it under the terms of the GNU5 * Lesser General Public License as published by the Free Software Foundation, either version 3 of6 * the License, or any later version.7 *8 * <p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;9 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10 * GNU Lesser General Public License for more details. A copy of the GNU Lesser General Public11 * License is distributed along with this program and can be found at12 * <http://www.gnu.org/licenses/lgpl.html>.13 */14package org.codice.ddf.admin.application.service.migratable;15import com.google.common.collect.ImmutableList;16import com.google.common.collect.ImmutableMap;17import java.io.IOException;18import java.io.InputStream;19import java.io.OutputStream;20import java.io.StringReader;21import java.io.StringWriter;22import java.nio.charset.Charset;23import java.nio.file.Path;24import java.nio.file.Paths;25import java.util.Collections;26import java.util.List;27import java.util.Optional;28import java.util.concurrent.atomic.AtomicInteger;29import org.apache.commons.io.input.ReaderInputStream;30import org.apache.commons.io.output.WriterOutputStream;31import org.apache.karaf.features.FeatureState;32import org.codice.ddf.migration.ExportMigrationContext;33import org.codice.ddf.migration.ExportMigrationEntry;34import org.codice.ddf.migration.ImportMigrationContext;35import org.codice.ddf.migration.ImportMigrationEntry;36import org.codice.ddf.migration.MigrationException;37import org.codice.ddf.migration.MigrationReport;38import org.codice.ddf.util.function.BiThrowingConsumer;39import org.hamcrest.Matchers;40import org.hamcrest.junit.internal.ThrowableMessageMatcher;41import org.junit.Assert;42import org.junit.Before;43import org.junit.Rule;44import org.junit.Test;45import org.junit.rules.ExpectedException;46import org.mockito.AdditionalAnswers;47import org.mockito.ArgumentCaptor;48import org.mockito.Mockito;49import org.mockito.stubbing.Answer;50import org.osgi.framework.Bundle;51import org.osgi.framework.Version;52import org.skyscreamer.jsonassert.JSONAssert;53public class ProfileMigratableTest {54  private static final Path PROFILE_PATH = Paths.get("profile.json");55  private static final String FEATURE_NAME = "feature.test.name";56  private static final String FEATURE_ID = "feature.test.id";57  private static final FeatureState FEATURE_STATE = FeatureState.Installed;58  private static final boolean FEATURE_REQUIRED = true;59  private static final int FEATURE_START = 57;60  private static final String FEATURE_REGION = "feature.test.region";61  private static final String FEATURE_REPOSITORY = "feature.test.repo";62  private static final long BUNDLE_ID = 14235L;63  private static final String BUNDLE_NAME = "bundle.test.name";64  private static final Version BUNDLE_VERSION = new Version(1, 2, 3, "bundle");65  private static final int BUNDLE_STATE = Bundle.STARTING;66  private static final String BUNDLE_LOCATION = "bundle.test.location";67  private static final JsonFeature JFEATURE =68      new JsonFeature(69          FEATURE_NAME,70          FEATURE_ID,71          null,72          null,73          FEATURE_STATE,74          FEATURE_REQUIRED,75          FEATURE_REGION,76          FEATURE_REPOSITORY,77          FEATURE_START);78  private static final JsonBundle JBUNDLE =79      new JsonBundle(BUNDLE_NAME, BUNDLE_VERSION, BUNDLE_ID, BUNDLE_STATE, BUNDLE_LOCATION);80  private static final String JSON_PROFILE_STR =81      JsonUtils.toJson(new JsonProfile(JFEATURE, JBUNDLE));82  private static final String JSON_PROFILE_FROM_MAP =83      JsonUtils.toJson(84          ImmutableMap.of(85              "features",86                  ImmutableList.of(87                      ImmutableMap.builder()88                          .put("name", FEATURE_NAME)89                          .put("id", FEATURE_ID)90                          .put("state", FEATURE_STATE)91                          .put("required", FEATURE_REQUIRED)92                          .put("region", FEATURE_REGION)93                          .put("repository", FEATURE_REPOSITORY)94                          .put("startLevel", FEATURE_START)95                          .build()),96              "bundles",97                  ImmutableList.of(98                      ImmutableMap.of(99                          "name", BUNDLE_NAME,100                          "id", BUNDLE_ID,101                          "version", BUNDLE_VERSION,102                          "state", BUNDLE_STATE,103                          "location", BUNDLE_LOCATION))));104  private final FeatureMigrator featureMigrator = Mockito.mock(FeatureMigrator.class);105  private final BundleMigrator bundleMigrator = Mockito.mock(BundleMigrator.class);106  private final MigrationReport report = Mockito.mock(MigrationReport.class);107  private final ProfileMigratable migratable =108      new ProfileMigratable(featureMigrator, bundleMigrator);109  private final ImportMigrationContext context = Mockito.mock(ImportMigrationContext.class);110  private final ImportMigrationEntry entry = Mockito.mock(ImportMigrationEntry.class);111  private final AtomicInteger importFeaturesAttempts = new AtomicInteger();112  private final AtomicInteger importBundlesAttempts = new AtomicInteger();113  @Rule public ExpectedException thrown = ExpectedException.none();114  @Before115  public void setup() {116    Mockito.doReturn(entry).when(context).getEntry(PROFILE_PATH);117    Mockito.doAnswer(callWithJson(report))118        .when(entry)119        .restore(120            Mockito121                .<BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>122                    notNull());123  }124  @Test125  public void testConstructorWithNullFeatureMigrator() throws Exception {126    thrown.expect(IllegalArgumentException.class);127    thrown.expectMessage(Matchers.containsString("null feature migrator"));128    new ProfileMigratable(null, bundleMigrator);129  }130  @Test131  public void testConstructorWithNullBundleMigrator() throws Exception {132    thrown.expect(IllegalArgumentException.class);133    thrown.expectMessage(Matchers.containsString("null bundle migrator"));134    new ProfileMigratable(featureMigrator, null);135  }136  @Test137  public void testGetVersion() throws Exception {138    Assert.assertThat(migratable.getVersion(), Matchers.notNullValue());139  }140  @Test141  public void testGetId() throws Exception {142    Assert.assertThat(migratable.getId(), Matchers.equalTo("ddf.profile"));143  }144  @Test145  public void testGetTitle() throws Exception {146    Assert.assertThat(migratable.getTitle(), Matchers.notNullValue());147  }148  @Test149  public void testGetDescription() throws Exception {150    Assert.assertThat(migratable.getDescription(), Matchers.notNullValue());151  }152  @Test153  public void testGetOrganization() throws Exception {154    Assert.assertThat(migratable.getOrganization(), Matchers.notNullValue());155  }156  @Test157  public void testDoExport() throws Exception {158    final ExportMigrationContext context = Mockito.mock(ExportMigrationContext.class);159    final ExportMigrationEntry entry = Mockito.mock(ExportMigrationEntry.class);160    final StringWriter sw = new StringWriter();161    Mockito.doReturn(entry).when(context).getEntry(PROFILE_PATH);162    Mockito.doReturn(Collections.singletonList(JFEATURE)).when(featureMigrator).exportFeatures();163    Mockito.doReturn(Collections.singletonList(JBUNDLE)).when(bundleMigrator).exportBundles();164    Mockito.doAnswer(165            AdditionalAnswers166                .<Boolean, BiThrowingConsumer<MigrationReport, OutputStream, IOException>>answer(167                    c -> { // callback the consumer168                      c.accept(169                          report, new WriterOutputStream(sw, Charset.defaultCharset(), 1024, true));170                      return true;171                    }))172        .when(entry)173        .store(Mockito.<BiThrowingConsumer<MigrationReport, OutputStream, IOException>>notNull());174    migratable.doExport(context);175    JSONAssert.assertEquals(JSON_PROFILE_FROM_MAP, sw.toString(), true);176    Mockito.verify(context).getEntry(PROFILE_PATH);177    Mockito.verify(entry)178        .store(Mockito.<BiThrowingConsumer<MigrationReport, OutputStream, IOException>>notNull());179    Mockito.verify(featureMigrator).exportFeatures();180    Mockito.verify(bundleMigrator).exportBundles();181  }182  @Test183  public void testDoImportWhenAllSucceedsInOnePass() throws Exception {184    initImportAttempts(ProfileMigratable.ATTEMPT_COUNT, ProfileMigratable.ATTEMPT_COUNT);185    Mockito.doAnswer(succeedsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());186    Mockito.doAnswer(187            succeedsImportAndStopRecordingTasksAtAttempt(188                importFeaturesAttempts, ProfileMigratable.ATTEMPT_COUNT - 1))189        .when(featureMigrator)190        .importFeatures(Mockito.notNull(), Mockito.notNull());191    Mockito.doAnswer(192            succeedsImportAndStopRecordingTasksAtAttempt(193                importBundlesAttempts, ProfileMigratable.ATTEMPT_COUNT - 1))194        .when(bundleMigrator)195        .importBundles(Mockito.notNull(), Mockito.notNull());196    migratable.doImport(context);197    verifyMigratorsImport(2, 2, true);198  }199  @Test200  public void testDoImportWhenFeaturesSucceedOnlyOnBeforeToFinalAttempt() throws Exception {201    initImportAttempts(ProfileMigratable.ATTEMPT_COUNT - 1, ProfileMigratable.ATTEMPT_COUNT - 1);202    Mockito.doAnswer(succeedsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());203    Mockito.doAnswer(succeedsImportOnLastAttempt(importFeaturesAttempts))204        .when(featureMigrator)205        .importFeatures(Mockito.notNull(), Mockito.notNull());206    Mockito.doAnswer(succeedsImportAndStopRecordingTasksAtAttempt(importBundlesAttempts, 0))207        .when(bundleMigrator)208        .importBundles(Mockito.notNull(), Mockito.notNull());209    migratable.doImport(context);210    verifyMigratorsImport(ProfileMigratable.ATTEMPT_COUNT, ProfileMigratable.ATTEMPT_COUNT, false);211  }212  @Test213  public void testDoImportWhenBundlesSucceedOnlyOnBeforeToFinalAttempt() throws Exception {214    initImportAttempts(1, ProfileMigratable.ATTEMPT_COUNT - 1);215    Mockito.doAnswer(succeedsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());216    Mockito.doAnswer(succeedsImportAndStopRecordingTasksAtAttempt(importFeaturesAttempts, 0))217        .when(featureMigrator)218        .importFeatures(Mockito.notNull(), Mockito.notNull());219    Mockito.doAnswer(succeedsImportOnLastAttempt(importBundlesAttempts))220        .when(bundleMigrator)221        .importBundles(Mockito.notNull(), Mockito.notNull());222    migratable.doImport(context);223    // importFeatures() will be called on last attempt and verification attempt only224    verifyMigratorsImport(2, ProfileMigratable.ATTEMPT_COUNT, false);225  }226  @Test227  public void testDoImportWhenFeaturesFailOnFirstPass() throws Exception {228    Mockito.doAnswer(failsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());229    Mockito.doReturn(false)230        .when(featureMigrator)231        .importFeatures(Mockito.notNull(), Mockito.notNull());232    Mockito.doReturn(true).when(bundleMigrator).importBundles(Mockito.notNull(), Mockito.notNull());233    migratable.doImport(context);234    verifyMigratorsImport(1, 1, true);235  }236  @Test237  public void testDoImportWhenBundlesFailOnFirstPass() throws Exception {238    Mockito.doAnswer(failsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());239    Mockito.doReturn(false)240        .when(featureMigrator)241        .importFeatures(Mockito.notNull(), Mockito.notNull());242    Mockito.doReturn(false)243        .when(bundleMigrator)244        .importBundles(Mockito.notNull(), Mockito.notNull());245    migratable.doImport(context);246    verifyMigratorsImport(0, 1, true);247  }248  @Test249  public void testDoImportWhenFeaturesNeverSucceed() throws Exception {250    initImportAttempts(0, ProfileMigratable.ATTEMPT_COUNT - 1);251    Mockito.doAnswer(succeedsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());252    Mockito.doAnswer(neverSucceedsImport())253        .when(featureMigrator)254        .importFeatures(Mockito.notNull(), Mockito.notNull());255    Mockito.doAnswer(succeedsImportAndStopRecordingTasksAtAttempt(importBundlesAttempts, 0))256        .when(bundleMigrator)257        .importBundles(Mockito.notNull(), Mockito.notNull());258    thrown.expect(IllegalStateException.class);259    thrown.expectMessage(Matchers.containsString("too many attempts"));260    migratable.doImport(context);261  }262  @Test263  public void testDoImportWhenBundlesNeverSucceed() throws Exception {264    initImportAttempts(1, 0);265    Mockito.doAnswer(succeedsWasSuccessful()).when(report).wasSuccessful(Mockito.notNull());266    Mockito.doAnswer(succeedsImportAndStopRecordingTasksAtAttempt(importFeaturesAttempts, 0))267        .when(featureMigrator)268        .importFeatures(Mockito.notNull(), Mockito.notNull());269    Mockito.doAnswer(neverSucceedsImport())270        .when(bundleMigrator)271        .importBundles(Mockito.notNull(), Mockito.notNull());272    thrown.expect(IllegalStateException.class);273    thrown.expectMessage(Matchers.containsString("too many attempts"));274    migratable.doImport(context);275  }276  @Test277  public void testDoImportWhenProfileWasNotExported() throws Exception {278    Mockito.doAnswer(callWithoutJson(report))279        .when(entry)280        .restore(281            Mockito282                .<BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>283                    notNull());284    Mockito.doReturn(report).when(context).getReport();285    Mockito.doReturn(report).when(report).record(Mockito.<MigrationException>notNull());286    migratable.doImport(context);287    final ArgumentCaptor<MigrationException> error =288        ArgumentCaptor.forClass(MigrationException.class);289    Mockito.verify(report).record(error.capture());290    Assert.assertThat(291        error.getValue(), // last one should be the too many attempts one292        ThrowableMessageMatcher.hasMessage(293            Matchers.containsString("missing exported profile information")));294  }295  private void initImportAttempts(int features, int bundles) {296    importFeaturesAttempts.set(features);297    importBundlesAttempts.set(bundles);298  }299  private void verifyMigratorsImport(int features, int bundles, boolean nofinals) {300    Mockito.verify(context).getEntry(PROFILE_PATH);301    Mockito.verify(entry)302        .restore(303            Mockito304                .<BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>305                    notNull());306    Mockito.verify(report, Mockito.times(Math.max(features, bundles)))307        .wasSuccessful(Mockito.notNull());308    final ArgumentCaptor<JsonProfile> jprofiles = ArgumentCaptor.forClass(JsonProfile.class);309    final ArgumentCaptor<ProfileMigrationReport> featureReports =310        ArgumentCaptor.forClass(ProfileMigrationReport.class);311    final ArgumentCaptor<ProfileMigrationReport> bundleReports =312        ArgumentCaptor.forClass(ProfileMigrationReport.class);313    Mockito.verify(featureMigrator, Mockito.times(features))314        .importFeatures(featureReports.capture(), jprofiles.capture());315    Mockito.verify(bundleMigrator, Mockito.times(bundles))316        .importBundles(bundleReports.capture(), jprofiles.capture());317    verifyReports(featureReports, features, nofinals);318    verifyReports(bundleReports, bundles, nofinals);319    jprofiles320        .getAllValues()321        .forEach(322            p -> {323              Assert.assertThat(324                  p.features().toArray(JsonFeature[]::new), Matchers.arrayContaining(JFEATURE));325              Assert.assertThat(326                  p.bundles().toArray(JsonBundle[]::new), Matchers.arrayContaining(JBUNDLE));327            });328  }329  private void verifyReports(330      ArgumentCaptor<ProfileMigrationReport> reports, int total, boolean nofinals) {331    final List<ProfileMigrationReport> rs = reports.getAllValues();332    Assert.assertThat(rs.size(), Matchers.equalTo(total));333    for (int i = 0; i < total; i++) {334      Assert.assertThat(335          rs.get(i).isFinalAttempt(), Matchers.equalTo(!nofinals && (i == total - 1)));336    }337  }338  private static Answer callWithJson(MigrationReport report) {339    return AdditionalAnswers340        .<Boolean, BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>answer(341            c -> {342              // callback the consumer343              c.accept(344                  report,345                  Optional.of(346                      new ReaderInputStream(347                          new StringReader(JSON_PROFILE_STR), Charset.defaultCharset())));348              return true;349            });350  }351  private static Answer callWithoutJson(MigrationReport report) {352    return AdditionalAnswers353        .<Boolean, BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>answer(354            c -> {355              // callback the consumer356              c.accept(report, Optional.empty());357              return true;358            });359  }360  private static Answer succeedsWasSuccessful() {361    return AdditionalAnswers.<Boolean, Runnable>answer(362        r -> {363          r.run();364          return true;365        });366  }367  private static Answer failsWasSuccessful() {368    return AdditionalAnswers.<Boolean, Runnable>answer(369        r -> {370          r.run();371          return false;372        });373  }374  private static Answer succeedsImportAndStopRecordingTasksAtAttempt(375      AtomicInteger attempts, int attempt) {376    return AdditionalAnswers.<Boolean, ProfileMigrationReport, JsonProfile>answer(377        (r, p) -> {378          if (attempts.getAndDecrement() > attempt) {379            r.recordTask();380          }381          return true;382        });383  }384  private static Answer succeedsImportOnLastAttempt(AtomicInteger attempts) {385    return AdditionalAnswers.<Boolean, ProfileMigrationReport, JsonProfile>answer(386        (r, p) -> {387          final int attempt = attempts.decrementAndGet();388          if (attempt <= 0) { // succeeds on last attempt only389            if (attempt == 0) {390              r.recordTask();391            } // else - don't record tasks on the verification attempt that will follow the last392            //          attempt393            return true;394          }395          r.recordTask();396          r.recordOnFinalAttempt(new MigrationException("testing import #" + (attempt + 1)));397          return false;398        });399  }400  private static Answer neverSucceedsImport() {401    return AdditionalAnswers.<Boolean, ProfileMigrationReport, JsonProfile>answer(402        (r, p) -> {403          r.recordTask();404          r.recordOnFinalAttempt(new MigrationException("testing import ..."));405          return false;406        });407  }408}...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    }...NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.junit.Test;3import static org.junit.Assert.*;4import static org.mockito.Mockito.*;5public class TestNotNull {6    public void testNotNull() {7        NotNull notNull = new NotNull();8        assertTrue(notNull.matches("notNull"));9        assertFalse(notNull.matches(null));10    }11}12OK (2 tests)NotNull
Using AI Code Generation
1import static org.mockito.internal.matchers.NotNull.notNull;2import static org.mockito.Mockito.*;3import org.mockito.internal.matchers.NotNull;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import org.junit.Test;7import static org.junit.Assert.*;8public class Test1 {9public void test1() {10    NotNull notNull = new NotNull();11    assertTrue(notNull.matches(null));12    assertFalse(notNull.matches("abc"));13}14}NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2public class NotNullTest {3    public static void main(String[] args) {4        NotNull notNull = new NotNull();5        System.out.println(notNull.matches("Hello World"));6    }7}NotNull
Using AI Code Generation
1public class Test {2    public void test() {3        NotNull notNull = new NotNull();4        notNull.matches(null);5    }6}7[ERROR] /home/akmo/GitHub/Test/1.java:5:17: Name 'notNull' must match pattern '^[a-z]([_a-z0-9]+)*$'. [LocalVariableName]8    <property name="format" value="^[a-z]([_a-z0-9]+)*$"/>9    <property name="format" value="^[a-z]([_a-z0-9]+)*$"/>NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.mockito.Mockito;3public class NotNullExample {4	public static void main(String[] args) {5		NotNull notNull = new NotNull();6		Mockito.when(notNull.matches("hello")).thenReturn(true);7	}8}NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2import org.mockito.internal.matchers.Null;3import static org.mockito.Mockito.*;4import org.junit.Test;5import static org.junit.Assert.*;6public class TestNotNull {7   public void testNotNull() {8      NotNull notNull = new NotNull();9      assertTrue(notNull.matches(null) == false);10      assertTrue(notNull.matches("notNull") == true);11   }12}NotNull
Using AI Code Generation
1public class MockitoNotNull {2  public static void main(String[] args) {3    NotNull notNull = new NotNull();4    System.out.println("Is null not null? " + notNull.matches(null));5    System.out.println("Is string not null? " + notNull.matches("test"));6  }7}NotNull
Using AI Code Generation
1import org.mockito.internal.matchers.NotNull;2public class Main {3    public static void main(String[] args) {4        new Main().test();5    }6    public void test() {7        foo(null);8    }9    public void foo(Object o) {10        NotNull notNull = new NotNull();11        if (!notNull.matches(o)) {12            throw new IllegalArgumentException("o is null");13        }14    }15}16import org.mockito.internal.matchers.NotNull;17public class Main {18    public static void main(String[] args) {19        new Main().test();20    }21    public void test() {22        foo(null);23    }24    public void foo(Object o) {25        NotNull notNull = new NotNull();26        if (!notNull.matches(o)) {27            throw new IllegalArgumentException("o is null");28        }29    }30}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!!
