How to use method of org.mockito.ArgumentMatchers class

Best Mockito code snippet using org.mockito.ArgumentMatchers.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Copyright 2020 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package org.chromium.chrome.browser.browserservices.permissiondelegation;
6
7import static org.junit.Assert.assertFalse;
8import static org.junit.Assert.assertTrue;
9import static org.mockito.ArgumentMatchers.any;
10import static org.mockito.ArgumentMatchers.anyBoolean;
11import static org.mockito.ArgumentMatchers.anyDouble;
12import static org.mockito.ArgumentMatchers.anyInt;
13import static org.mockito.ArgumentMatchers.anyString;
14import static org.mockito.ArgumentMatchers.eq;
15import static org.mockito.Mockito.doAnswer;
16import static org.mockito.Mockito.never;
17import static org.mockito.Mockito.verify;
18
19import android.os.Bundle;
20
21import androidx.browser.trusted.TrustedWebActivityCallback;
22
23import org.junit.Before;
24import org.junit.Rule;
25import org.junit.Test;
26import org.junit.runner.RunWith;
27import org.mockito.Mock;
28import org.mockito.MockitoAnnotations;
29import org.robolectric.annotation.Config;
30
31import org.chromium.base.test.BaseRobolectricTestRunner;
32import org.chromium.base.test.util.Feature;
33import org.chromium.base.test.util.JniMocker;
34import org.chromium.chrome.browser.browserservices.TrustedWebActivityClient;
35import org.chromium.chrome.browser.flags.ChromeFeatureList;
36import org.chromium.chrome.test.util.browser.Features.EnableFeatures;
37import org.chromium.components.embedder_support.util.Origin;
38
39/**
40 * Tests for {@link InstalledWebappGeolocationBridge}.
41 */
42@RunWith(BaseRobolectricTestRunner.class)
43@Config(manifest = Config.NONE)
44@EnableFeatures(ChromeFeatureList.TRUSTED_WEB_ACTIVITY_LOCATION_DELEGATION)
45public class InstalledWebappGeolocationBridgeTest {
46    private static final Origin ORIGIN = Origin.create("https://www.website.com");
47    private static final Origin OTHER_ORIGIN = Origin.create("https://www.other.website.com");
48    private static final String EXTRA_CALLBACK = "extraCallback";
49
50    private static final long NATIVE_POINTER = 12;
51
52    @Rule
53    public JniMocker mocker = new JniMocker();
54
55    @Mock
56    private TrustedWebActivityClient mTrustedWebActivityClient;
57    @Mock
58    private InstalledWebappGeolocationBridge.Natives mNativeMock;
59
60    private InstalledWebappGeolocationBridge mGeolocation;
61
62    private boolean mIsHighAccuracy = false;
63
64    @Before
65    public void setUp() {
66        MockitoAnnotations.initMocks(this);
67        mocker.mock(InstalledWebappGeolocationBridgeJni.TEST_HOOKS, mNativeMock);
68
69        mGeolocation = new InstalledWebappGeolocationBridge(
70                NATIVE_POINTER, ORIGIN, mTrustedWebActivityClient);
71    }
72
73    @Test
74    @Feature("TrustedWebActivities")
75    public void getLocationError_whenClientDoesntHaveService() {
76        uninstallTrustedWebActivityService(ORIGIN);
77        mGeolocation.start(false /* HighAccuracy */);
78        verifyGetLocationError();
79    }
80
81    @Test
82    @Feature("TrustedWebActivities")
83    public void getLocationUpdate_afterStartListening() {
84        installTrustedWebActivityService(ORIGIN);
85        mGeolocation.start(false /* HighAccuracy */);
86        verifyGetLocationUpdate();
87    }
88
89    @Test
90    @Feature("TrustedWebActivities")
91    public void noLocationUpdate_stopBeforeStart() {
92        installTrustedWebActivityService(ORIGIN);
93        mGeolocation.stopAndDestroy();
94        mGeolocation.start(false /* HighAccuracy */);
95        verifyNoLocationUpdate();
96    }
97
98    @Test
99    @Feature("TrustedWebActivities")
100    public void getLocationError_whenOnlytherClientHasService() {
101        installTrustedWebActivityService(OTHER_ORIGIN);
102        uninstallTrustedWebActivityService(ORIGIN);
103        mGeolocation.start(false /* HighAccuracy */);
104        verifyGetLocationError();
105        verifyNoLocationUpdate();
106    }
107
108    @Test
109    @Feature("TrustedWebActivities")
110    public void changeHighAccuracyAfterStart() {
111        installTrustedWebActivityService(ORIGIN);
112        mGeolocation.start(false /* HighAccuracy */);
113        assertFalse(mIsHighAccuracy);
114        mGeolocation.start(true /* HighAccuracy */);
115        assertTrue(mIsHighAccuracy);
116    }
117
118    /** "Installs" a Trusted Web Activity Service for the origin. */
119    @SuppressWarnings("unchecked")
120    private void installTrustedWebActivityService(Origin origin) {
121        doAnswer(invocation -> {
122            TrustedWebActivityCallback callback = invocation.getArgument(2);
123            mIsHighAccuracy = invocation.getArgument(1);
124
125            Bundle result = new Bundle();
126            // Put arbitrary value to test the result bundle is converted correctly.
127            // These value may not be valid geolocation data.
128            result.putDouble("latitude", 1.0d);
129            result.putDouble("longitude", -2.1d);
130            result.putLong("timeStamp", 30);
131            result.putDouble("altitude", 4.0d);
132            result.putDouble("accuracy", 5.3d);
133            result.putDouble("bearing", -6.4d);
134            result.putDouble("speed", 7.5d);
135
136            callback.onExtraCallback(
137                    InstalledWebappGeolocationBridge.EXTRA_NEW_LOCATION_AVAILABLE_CALLBACK, result);
138            return true;
139        })
140                .when(mTrustedWebActivityClient)
141                .startListeningLocationUpdates(eq(origin), anyBoolean(), any());
142    }
143
144    private void uninstallTrustedWebActivityService(Origin origin) {
145        doAnswer(invocation -> {
146            TrustedWebActivityCallback callback = invocation.getArgument(2);
147            Bundle error = new Bundle();
148            error.putString("message", "any errro message");
149            callback.onExtraCallback(
150                    InstalledWebappGeolocationBridge.EXTRA_NEW_LOCATION_ERROR_CALLBACK, error);
151            return true;
152        })
153                .when(mTrustedWebActivityClient)
154                .startListeningLocationUpdates(eq(origin), anyBoolean(), any());
155    }
156
157    // Verify native gets location update with correct value.
158    private void verifyGetLocationUpdate() {
159        verify(mNativeMock)
160                .onNewLocationAvailable(eq(NATIVE_POINTER), eq(1.0d), eq(-2.1d), eq(0.03d),
161                        eq(true), eq(4.0d), eq(true), eq(5.3d), eq(true), eq(-6.4d), eq(true),
162                        eq(7.5d));
163    }
164
165    private void verifyGetLocationError() {
166        verify(mNativeMock).onNewErrorAvailable(eq(NATIVE_POINTER), anyString());
167    }
168
169    private void verifyNoLocationUpdate() {
170        verify(mNativeMock, never())
171                .onNewLocationAvailable(anyInt(), anyDouble(), anyDouble(), anyDouble(),
172                        anyBoolean(), anyDouble(), anyBoolean(), anyDouble(), anyBoolean(),
173                        anyDouble(), anyBoolean(), anyDouble());
174    }
175}
176
Full Screen
copy
1package org.intercorpretail.challenge.retail.business;
2
3import org.intercorpretail.challenge.retail.repository.OrderRepository;
4import org.intercorpretail.challenge.retail.repository.entity.Order;
5import org.junit.jupiter.api.Test;
6import org.junit.jupiter.api.extension.ExtendWith;
7import org.mockito.InjectMocks;
8import org.mockito.Mock;
9import org.mockito.Mockito;
10import org.mockito.junit.jupiter.MockitoExtension;
11import reactor.core.publisher.Flux;
12
13import java.time.LocalDateTime;
14
15import static org.junit.jupiter.api.Assertions.*;
16import static org.mockito.ArgumentMatchers.any;
17import static org.mockito.ArgumentMatchers.anyDouble;
18import static org.mockito.ArgumentMatchers.anyString;
19
20@ExtendWith(MockitoExtension.class)
21class OrderServiceImplTest {
22
23    @InjectMocks
24    OrderServiceImpl orderService;
25
26    @Mock
27    OrderRepository orderRepository;
28
29    @Test
30    void testSave_GivenValidInputs_ShouldReturnNothing() {
31
32        Order order = Order.builder()
33                .userId("userId")
34                .total(2.0)
35                .subTotal(2.0)
36                .id("id")
37                .taxes(2.0)
38                .discounts(2.0)
39                .createdDate(LocalDateTime.now())
40                .build();
41
42        Flux<Integer> databaseResponse = Flux.just(1);
43
44        Mockito.when(this.orderRepository.insertOrder(anyString(), anyString(), anyDouble(), anyDouble(), anyDouble(), anyDouble(), any(LocalDateTime.class))).thenReturn(databaseResponse);
45
46        this.orderService.save(order);
47        Mockito.verify(this.orderRepository, Mockito.times(1)).insertOrder(anyString(), anyString(), anyDouble(), anyDouble(), anyDouble(), anyDouble(), any(LocalDateTime.class));
48    }
49}
Full Screen
copy
1package com.polestar.bridges.services;
2
3import com.polestar.bridges.Daos.BridgeRepository;
4import com.polestar.bridges.entities.Bridge;
5import com.polestar.bridges.exception.LatAndLongAlreadyExistException;
6import com.polestar.bridges.exception.NameAlreadyExistException;
7import org.junit.jupiter.api.BeforeEach;
8import org.junit.jupiter.api.Test;
9import org.junit.jupiter.api.TestInstance;
10import org.mockito.ArgumentMatchers;
11import org.mockito.Mockito;
12import org.springframework.util.Assert;
13
14import static org.mockito.Mockito.*;
15
16import java.util.ArrayList;
17import java.util.List;
18
19@TestInstance(TestInstance.Lifecycle.PER_CLASS)
20public class BridgeServiceTest {
21
22    private BridgeRepository bridgeRepository;
23    private BridgeService bridgeService;
24
25    @BeforeEach
26    public void initEachTest(){
27        bridgeRepository = Mockito.mock(BridgeRepository.class);
28        bridgeService = new BridgeServiceImp(bridgeRepository);
29    }
30
31
32    @Test
33    public void testAddBridgeSuccess(){
34        Bridge bridgeToAdd = new Bridge(1,2,3,4,56,"London Bridge");
35
36
37        when(bridgeRepository.findBridgeByName(ArgumentMatchers.anyString())).thenReturn(null);
38        when(bridgeRepository.findBridgeByLatitudeAndLongitude(ArgumentMatchers.anyDouble(),ArgumentMatchers.anyDouble())).thenReturn(null);
39        when(bridgeRepository.save(ArgumentMatchers.any(Bridge.class))).thenReturn(bridgeToAdd);
40
41        Assert.isInstanceOf(Bridge.class, bridgeService.addBridge(bridgeToAdd), "Should return a bridge");
42        verify(bridgeRepository,times(1)).findBridgeByName(ArgumentMatchers.anyString());
43        verify(bridgeRepository,times(1)).findBridgeByLatitudeAndLongitude(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble());
44        verify(bridgeRepository,times(1)).save(ArgumentMatchers.any(Bridge.class));
45    }
46
47    @Test
48    public void testAddBridgeFailedNameAlreadyExist(){
49        Bridge bridgeToAdd = new Bridge(1,2,3,4,56,"London Bridge");
50
51
52        when(bridgeRepository.findBridgeByName(ArgumentMatchers.anyString())).thenReturn(bridgeToAdd);
53
54        try{
55            bridgeService.addBridge(bridgeToAdd);
56        }catch (Exception e){
57            Assert.isInstanceOf(NameAlreadyExistException.class, e, "Should return exception when name already exist");
58        }
59        verify(bridgeRepository,times(1)).findBridgeByName(ArgumentMatchers.anyString());
60        verify(bridgeRepository,times(0)).findBridgeByLatitudeAndLongitude(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble());
61        verify(bridgeRepository,times(0)).save(ArgumentMatchers.any(Bridge.class));
62    }
63
64    @Test
65    public void testAddBridgeFailedLocationOccupied(){
66        Bridge bridgeToAdd = new Bridge(1,2,3,4,56,"London Bridge");
67        Bridge bridgeDB = new Bridge(1,2,3,4,56,"Rio Bridge");
68
69
70        when(bridgeRepository.findBridgeByName(ArgumentMatchers.anyString())).thenReturn(null);
71        when(bridgeRepository.findBridgeByLatitudeAndLongitude(ArgumentMatchers.anyDouble(),ArgumentMatchers.anyDouble())).thenReturn(bridgeDB);
72
73        try{
74            bridgeService.addBridge(bridgeToAdd);
75        }catch (Exception e){
76            Assert.isInstanceOf(LatAndLongAlreadyExistException.class, e, "Should return exception when location already occupied");
77        }
78        verify(bridgeRepository,times(1)).findBridgeByName(ArgumentMatchers.anyString());
79        verify(bridgeRepository,times(1)).findBridgeByLatitudeAndLongitude(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble());
80        verify(bridgeRepository,times(0)).save(ArgumentMatchers.any(Bridge.class));
81    }
82
83    @Test
84    public void testGetAllBridges() {
85        Bridge bridgeDB1 = new Bridge(1,2,3,78,56,"Rio Bridge");
86        Bridge bridgeDB2 = new Bridge(1,2,3,4,20,"Denver Bridge");
87
88        List<Bridge> databaseResponse = new ArrayList<>();
89        databaseResponse.add(bridgeDB1);
90        databaseResponse.add(bridgeDB2);
91
92        when(bridgeRepository.findAll()).thenReturn(databaseResponse);
93
94        Assert.isInstanceOf(ArrayList.class, bridgeService.getAllBridges(), "Should return a list of bridges");
95    }
96
97}
98
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)