Best Mockito code snippet using org.mockito.Mockito.mockitoSession
Source:OsuServerConnectionTest.java
...117 */118 @Test119 public void verifyInitAndConnect() throws Exception {120 // static mocking121 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(122 ServiceProviderVerifier.class).startMocking();123 try {124 when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(125 mProviderIdentities);126 establishServerConnection();127 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();128 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];129 trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);130 verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(true));131 Map<String, String> providerNames = new HashMap<>();132 providerNames.put(Locale.US.getISO3Language(), PROVIDER_NAME_VALID);133 assertTrue(mOsuServerConnection.validateProvider(providerNames));134 } finally {135 session.finishMocking();136 }137 }138 /**139 * Verifies multiple languages of OsuProvider names are matched with cert140 */141 @Test142 public void verifyValidateProviderWithMultipleProviderLangs() throws Exception {143 // static mocking144 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(145 ServiceProviderVerifier.class).startMocking();146 try {147 when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(148 mProviderIdentities);149 establishServerConnection();150 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();151 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];152 trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);153 Map<String, String> friendlyNames = new HashMap<>();154 friendlyNames.put(155 Locale.SIMPLIFIED_CHINESE.getISO3Language(), TEST_PROVIDER_CHINESE_NAME);156 friendlyNames.put(Locale.US.getISO3Language(), PROVIDER_NAME_VALID);157 assertTrue(mOsuServerConnection.validateProvider(friendlyNames));158 } finally {159 session.finishMocking();160 }161 }162 /**163 * Verifies wrong language of OsuProvider name is mismatched with cert164 */165 @Test166 public void verifyValidateProviderWithMismatchedProviderLang() throws Exception {167 // static mocking168 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(169 ServiceProviderVerifier.class).startMocking();170 try {171 when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(172 mProviderIdentities);173 establishServerConnection();174 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();175 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];176 trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);177 Map<String, String> friendlyNames = new HashMap<>();178 friendlyNames.put(179 Locale.SIMPLIFIED_CHINESE.getISO3Language(), TEST_PROVIDER_CHINESE_NAME);180 assertFalse(mOsuServerConnection.validateProvider(friendlyNames));181 } finally {182 session.finishMocking();183 }184 }185 /**186 * Verifies same language from different regions.187 */188 @Test189 public void verifyValidateProviderWithSameLangButDifferentRegion() throws Exception {190 // static mocking191 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(192 ServiceProviderVerifier.class).startMocking();193 try {194 when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(195 mProviderIdentities);196 establishServerConnection();197 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();198 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];199 trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);200 Map<String, String> friendlyNames = new HashMap<>();201 friendlyNames.put(202 Locale.CANADA.getISO3Language(), PROVIDER_NAME_VALID);203 assertTrue(mOsuServerConnection.validateProvider(friendlyNames));204 } finally {205 session.finishMocking();206 }207 }208 /**209 * Verifies initialization of the HTTPS connection with invalid TLSContext210 */211 @Test212 public void verifyInvalidTlsContext() {213 mOsuServerConnection.init(null, mDelegate);214 mOsuServerConnection.setEventCallback(mOsuServerCallbacks);215 assertFalse(mOsuServerConnection.canValidateServer());216 }217 /**218 * Verifies initialization of the HTTPS connection when TlsContext init fails219 */220 @Test221 public void verifyTlsContextInitFailure() throws Exception {222 doThrow(new KeyManagementException()).when(mTlsContext).init(any(), any(), any());223 mOsuServerConnection.init(mTlsContext, mDelegate);224 mOsuServerConnection.setEventCallback(mOsuServerCallbacks);225 assertFalse(mOsuServerConnection.canValidateServer());226 }227 /**228 * Verifies initialization and opening URL connection failed on the network229 */230 @Test231 public void verifyInitAndNetworkOpenURLConnectionFailed() throws Exception {232 doThrow(new IOException()).when(mNetwork).openConnection(any(URL.class));233 mOsuServerConnection.init(mTlsContext, mDelegate);234 mOsuServerConnection.setEventCallback(mOsuServerCallbacks);235 assertTrue(mOsuServerConnection.canValidateServer());236 assertTrue(mOsuServerConnection.connect(mServerUrl, mNetwork));237 mLooper.dispatchAll();238 verify(mOsuServerCallbacks).onServerConnectionStatus(anyInt(), eq(false));239 }240 /**241 * Verifies initialization and connection failure to OSU server242 */243 @Test244 public void verifyInitAndServerConnectFailure() throws Exception {245 doThrow(new IOException()).when(mUrlConnection).connect();246 mOsuServerConnection.init(mTlsContext, mDelegate);247 mOsuServerConnection.setEventCallback(mOsuServerCallbacks);248 assertTrue(mOsuServerConnection.canValidateServer());249 assertTrue(mOsuServerConnection.connect(mServerUrl, mNetwork));250 mLooper.dispatchAll();251 verify(mOsuServerCallbacks).onServerConnectionStatus(anyInt(), eq(false));252 }253 /**254 * Verifies initialization and connecting to the OSU server, cert validation failure255 */256 @Test257 public void verifyInitAndConnectCertValidationFailure() throws Exception {258 establishServerConnection();259 List<X509Certificate> certificateList = PasspointProvisioningTestUtil.getOsuCertsForTest();260 X509Certificate[] certificates = new X509Certificate[1];261 certificates[0] = certificateList.get(0);262 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();263 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];264 doThrow(new CertificateException()).when(mDelegate)265 .getTrustedChainForServer(any(X509Certificate[].class), anyString(),266 (Socket) isNull());267 trustManager.checkServerTrusted(certificates, AUTH_TYPE);268 verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(false));269 }270 /**271 * Verifies initialization and connecting to the OSU server, friendly name mismatch272 */273 @Test274 public void verifyInitAndConnectInvalidProviderIdentity()throws Exception {275 // static mocking276 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(277 ServiceProviderVerifier.class).startMocking();278 try {279 when(ServiceProviderVerifier.getProviderNames(any(X509Certificate.class))).thenReturn(280 mProviderIdentities);281 establishServerConnection();282 TrustManager[] trustManagers = mTrustManagerCaptor.getValue();283 X509TrustManager trustManager = (X509TrustManager) trustManagers[0];284 trustManager.checkServerTrusted(new X509Certificate[1], AUTH_TYPE);285 verify(mOsuServerCallbacks).onServerValidationStatus(anyInt(), eq(true));286 Map<String, String> providerNames = new HashMap<>();287 providerNames.put(Locale.US.getISO3Language(), PROVIDER_NAME_INVALID);288 assertFalse(mOsuServerConnection.validateProvider(providerNames));289 } finally {290 session.finishMocking();291 }292 }293 /**294 * Verifies {@code ExchangeSoapMessage} should return {@code false} if there is no connection.295 */296 @Test297 public void verifyExchangeSoapMessageWithoutConnection() {298 assertFalse(mOsuServerConnection.exchangeSoapMessage(299 new SoapSerializationEnvelope(SoapEnvelope.VER12)));300 }301 /**302 * Verifies {@code ExchangeSoapMessage} should return {@code false} if {@code soapEnvelope} is303 * {@code null}304 */305 @Test306 public void verifyExchangeSoapMessageWithInvalidArgument() throws Exception {307 establishServerConnection();308 assertFalse(mOsuServerConnection.exchangeSoapMessage(null));309 }310 /**311 * Verifies {@code ExchangeSoapMessage} should get {@code null} message if exception occurs312 * during soap exchange.313 */314 @Test315 public void verifyExchangeSoapMessageWithException() throws Exception {316 // static mocking317 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(318 HttpsTransport.class).startMocking();319 try {320 establishServerConnection();321 when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(322 mHttpsTransport);323 doThrow(new IOException()).when(mHttpsTransport).call(any(String.class),324 any(SoapSerializationEnvelope.class));325 assertTrue(mOsuServerConnection.exchangeSoapMessage(326 new SoapSerializationEnvelope(SoapEnvelope.VER12)));327 mLooper.dispatchAll();328 verify(mOsuServerCallbacks).onReceivedSoapMessage(anyInt(), isNull());329 } finally {330 session.finishMocking();331 }332 }333 /**334 * Verifies {@code ExchangeSoapMessage} should return an instance of {@link SppResponseMessage}.335 */336 @Test337 public void verifyExchangeSoapMessage() throws Exception {338 // static mocking339 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(340 HttpsTransport.class).mockStatic(SoapParser.class).startMocking();341 try {342 establishServerConnection();343 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);344 envelope.bodyIn = new SoapObject();345 when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(346 mHttpsTransport);347 when(SoapParser.getResponse(any(SoapObject.class))).thenReturn(mSppResponseMessage);348 assertTrue(mOsuServerConnection.exchangeSoapMessage(envelope));349 mLooper.dispatchAll();350 verify(mOsuServerCallbacks).onReceivedSoapMessage(anyInt(), eq(mSppResponseMessage));351 } finally {352 session.finishMocking();353 }354 }355 /**356 * Verifies {@code retrieveTrustRootCerts} should return {@code false} if there is no357 * connection.358 */359 @Test360 public void verifyRetrieveTrustRootCertsWithoutConnection() {361 assertFalse(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));362 }363 /**364 * Verifies {@code retrieveTrustRootCerts} should return {@code false} if {@code365 * mTrustCertsInfo} is empty.366 */367 @Test368 public void verifyRetrieveTrustRootCertsWithEmptyOfTrustCertsInfo() {369 mOsuServerConnection.init(mTlsContext, mDelegate);370 mOsuServerConnection.setEventCallback(mOsuServerCallbacks);371 assertFalse(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));372 }373 /**374 * Verifies it should return an empty collection of CA certificates if HTTPS response from375 * server to get root CA certificate is not HTTP OK.376 */377 @Test378 public void verifyRetrieveTrustRootCertsWithErrorInHTTPSResponse() throws Exception {379 // static mocking380 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(381 HttpsTransport.class).startMocking();382 try {383 when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(384 mHttpsTransport);385 when(mHttpsServiceConnection.getResponseCode()).thenReturn(386 HttpURLConnection.HTTP_NO_CONTENT);387 ArgumentCaptor<Map<Integer, List<X509Certificate>>> argumentCaptor =388 ArgumentCaptor.forClass(Map.class);389 // Test Data390 Map<String, byte[]> certInfo = new HashMap<>();391 certInfo.put("https://test.com/trustroot", "testData".getBytes());392 certInfo.put("https://test2.com/trustroot", "testData2".getBytes());393 mTrustCertsInfo.put(OsuServerConnection.TRUST_CERT_TYPE_AAA, certInfo);394 establishServerConnection();395 assertTrue(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));396 mLooper.dispatchAll();397 verify(mOsuServerCallbacks).onReceivedTrustRootCertificates(anyInt(),398 argumentCaptor.capture());399 assertTrue(argumentCaptor.getValue().isEmpty());400 } finally {401 session.finishMocking();402 }403 }404 /**405 * Verifies it should return a collection of CA certificates if there is no error while406 * downloading root CA certificate from each {@code URL} provided407 */408 @Test409 public void verifyRetrieveTrustRootCertsWithoutError() throws Exception {410 // static mocking411 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(412 HttpsTransport.class).mockStatic(CertificateFactory.class).mockStatic(413 ServiceProviderVerifier.class).startMocking();414 try {415 X509Certificate certificate = Mockito.mock(X509Certificate.class);416 InputStream inputStream = Mockito.mock(InputStream.class);417 // To avoid infinite loop in OsuServerConnection.getCert.418 when(inputStream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1);419 CertificateFactory certificateFactory = Mockito.mock(CertificateFactory.class);420 when(certificateFactory.generateCertificate(any(InputStream.class))).thenReturn(421 certificate);422 when(CertificateFactory.getInstance(anyString())).thenReturn(certificateFactory);423 when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(424 mHttpsTransport);425 when(mHttpsServiceConnection.getResponseCode()).thenReturn(426 HttpURLConnection.HTTP_OK);427 when(mHttpsServiceConnection.openInputStream()).thenReturn(inputStream);428 ArgumentCaptor<Map<Integer, List<X509Certificate>>> argumentCaptor =429 ArgumentCaptor.forClass(Map.class);430 when(ServiceProviderVerifier.verifyCertFingerprint(any(X509Certificate.class),431 any(byte[].class))).thenReturn(true);432 // Test Data433 Map<String, byte[]> certInfo = new HashMap<>();434 certInfo.put("https://test.com/trustroot", "testData".getBytes());435 mTrustCertsInfo.put(OsuServerConnection.TRUST_CERT_TYPE_AAA, certInfo);436 List<HeaderProperty> properties = new ArrayList<>();437 // Indicates that X.509 CA certificate is included.438 properties.add(new HeaderProperty("Content-Type", "application/x-x509-ca-cert"));439 when(mHttpsServiceConnection.getResponseProperties()).thenReturn(properties);440 establishServerConnection();441 assertTrue(mOsuServerConnection.retrieveTrustRootCerts(mTrustCertsInfo));442 mLooper.dispatchAll();443 verify(mOsuServerCallbacks).onReceivedTrustRootCertificates(anyInt(),444 argumentCaptor.capture());445 Assert.assertEquals(1, argumentCaptor.getValue().size());446 Assert.assertEquals(certificate,447 argumentCaptor.getValue().get(OsuServerConnection.TRUST_CERT_TYPE_AAA).get(0));448 } finally {449 session.finishMocking();450 }451 }452 /**453 * Verifies that cleanup is properly called on the OsuServerHandlerThread.454 */455 @Test456 public void verifyCleanup() throws Exception {457 // static mocking458 MockitoSession session = ExtendedMockito.mockitoSession().mockStatic(459 HttpsTransport.class).mockStatic(SoapParser.class).startMocking();460 try {461 establishServerConnection();462 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);463 envelope.bodyIn = new SoapObject();464 when(HttpsTransport.createInstance(any(Network.class), any(URL.class))).thenReturn(465 mHttpsTransport);466 when(SoapParser.getResponse(any(SoapObject.class))).thenReturn(mSppResponseMessage);467 assertTrue(mOsuServerConnection.exchangeSoapMessage(envelope));468 mLooper.dispatchAll();469 verify(mHttpsServiceConnection).disconnect();470 reset(mHttpsServiceConnection);471 mOsuServerConnection.cleanup();472 mLooper.dispatchAll();...
Source:ExampleInstrumentedTest.java
...8import org.junit.runner.RunWith;9import org.mockito.MockitoSession;10import static android.provider.Settings.Global.DEVICE_NAME;11import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;12import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;13import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;14import static com.android.dx.mockito.inline.extended.ExtendedMockito.staticMockMarker;15import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;16import static org.junit.Assert.*;17import static org.mockito.ArgumentMatchers.any;18import static org.mockito.ArgumentMatchers.eq;19import static org.mockito.Mockito.atLeast;20import static org.mockito.Mockito.atLeastOnce;21import static org.mockito.Mockito.atMost;22import static org.mockito.Mockito.mock;23import static org.mockito.Mockito.reset;24import static org.mockito.Mockito.spy;25import static org.mockito.Mockito.times;26import static org.mockito.Mockito.when;27@RunWith(AndroidJUnit4.class)28public class ExampleInstrumentedTest {29 private static class SuperClass {30 final String returnA() {31 return "superA";32 }33 static String returnB() {34 return "superB";35 }36 static String returnC() {37 return "superC";38 }39 }40 private static final class SubClass extends SuperClass {41 static String recorded = null;42 static String returnC() {43 return "subC";44 }45 static final String record(String toRecord) {46 recorded = toRecord;47 return "record";48 }49 }50 @Test51 public void mockingExample() {52 assertEquals("superB", SuperClass.returnB());53 MockitoSession session = mockitoSession().mockStatic(SuperClass.class).startMocking();54 try {55 assertNull(SuperClass.returnB());56 when(SubClass.returnB()).thenReturn("fakeB");57 assertEquals("fakeB", SuperClass.returnB());58 } finally {59 session.finishMocking();60 }61 }62 @Test63 public void spyStatic() throws Exception {64 ContentResolver resolver = InstrumentationRegistry.getTargetContext().getContentResolver();65 String deviceName = Settings.Global.getString(resolver, DEVICE_NAME);66 MockitoSession session = mockitoSession().spyStatic(Settings.Global.class).startMocking();67 try {68 // Cannot call when(Settings.getString(any(ContentResolver.class), eq("...")))69 // as any(ContentResolver.class) returns null which makes getString fail. Hence need to70 // use less lambda API71 doReturn("23").when(() -> Settings.Global.getString(any72 (ContentResolver.class), eq("twenty three")));73 doReturn(42).when(() -> Settings.Global.getInt(any74 (ContentResolver.class), eq("fourty two")));75 // Make sure behavior is changed76 assertEquals("23", Settings.Global.getString(resolver, "twenty three"));77 assertEquals(42, Settings.Global.getInt(resolver, "fourty two"));78 // Make sure non-mocked methods work as before79 assertEquals(deviceName, Settings.Global.getString(resolver, DEVICE_NAME));80 } finally {81 session.finishMocking();82 }83 }84 @Test85 public void resetMock() throws Exception {86 MockitoSession session = mockitoSession().mockStatic(SuperClass.class).startMocking();87 try {88 assertNull(SuperClass.returnB());89 when(SuperClass.returnB()).thenReturn("fakeB");90 assertEquals("fakeB", SuperClass.returnB());91 reset(staticMockMarker(SuperClass.class));92 assertNull(SuperClass.returnB());93 } finally {94 session.finishMocking();95 }96 }97 @Test98 public void mockOverriddenStaticMethod() throws Exception {99 MockitoSession session = mockitoSession().mockStatic(SubClass.class).startMocking();100 try {101 // By default all static methods of the mocked class should return the default answers102 assertNull(SubClass.returnB());103 assertNull(SubClass.returnC());104 // Super class is not mocked105 assertEquals("superB", SuperClass.returnB());106 assertEquals("superC", SuperClass.returnC());107 when(SubClass.returnB()).thenReturn("fakeB");108 when(SubClass.returnC()).thenReturn("fakeC");109 // Make sure behavior is changed110 assertEquals("fakeB", SubClass.returnB());111 assertEquals("fakeC", SubClass.returnC());112 // Super class should not be affected113 assertEquals("superB", SuperClass.returnB());114 assertEquals("superC", SuperClass.returnC());115 } finally {116 session.finishMocking();117 }118 // Mocking should be stopped119 assertEquals("superB", SubClass.returnB());120 assertEquals("subC", SubClass.returnC());121 }122 @Test123 public void mockSuperMethod() throws Exception {124 MockitoSession session = mockitoSession().mockStatic(SuperClass.class).startMocking();125 try {126 // By default all static methods of the mocked class should return the default answers127 assertNull(SuperClass.returnB());128 assertNull(SuperClass.returnC());129 // Sub class should not be affected130 assertEquals("superB", SubClass.returnB());131 assertEquals("subC", SubClass.returnC());132 when(SuperClass.returnB()).thenReturn("fakeB");133 when(SuperClass.returnC()).thenReturn("fakeC");134 // Make sure behavior is changed135 assertEquals("fakeB", SuperClass.returnB());136 assertEquals("fakeC", SuperClass.returnC());137 // Sub class should not be affected138 assertEquals("superB", SubClass.returnB());139 assertEquals("subC", SubClass.returnC());140 } finally {141 session.finishMocking();142 }143 // Mocking should be stopped144 assertEquals("superB", SuperClass.returnB());145 assertEquals("superC", SuperClass.returnC());146 }147 class FinalTrojan {148 final String finalOpen() { return "horse"; }149 }150 @Test151 public void testStubbingFinalMethod() {152 FinalTrojan mockF = mock(FinalTrojan.class);153 when(mockF.finalOpen()).thenReturn("soldiers");154 assertEquals("soldiers", mockF.finalOpen());155 }156 class T {157 String echo(String in) {158 return in;159 }160 }161 @Test162 public void testStubbing() {163 T mockT = mock(T.class);164 // mock objects return a default value when not stubbed165 assertNull(mockT.echo("Marco"));166 when(mockT.echo("Marco")).thenReturn("Polo");167 assertEquals("Polo", mockT.echo("Marco"));168 }169 @Test170 public void testStubbingOnSpy() {171 T spyT = spy(new T());172 assertEquals("Marco", spyT.echo("Marco"));173 when(spyT.echo("Marco")).thenReturn("Polo");174 assertEquals("Polo", spyT.echo("Marco"));175 }176 class F {177 final String finalEcho(String in) {178 return in;179 }180 }181 static class S {182 static String staticEcho(String in) {183 return in;184 }185 }186 @Test187 public void testStubbingStaticMethod() {188 MockitoSession session = mockitoSession().mockStatic(S.class).startMocking();189 try {190 when(S.staticEcho("Marco")).thenReturn("Polo");191 assertEquals("Polo", S.staticEcho("Marco"));192 } finally {193 session.finishMocking();194 }195 // Once the session is finished, all stubbings are reset196 assertEquals("Marco", S.staticEcho("Marco"));197 }198 @Test199 public void testSpyOn() {200 T originalT = new T();201 spyOn(originalT); // Returns void202 when(originalT.echo("Marco")).thenReturn("Polo");203 assertEquals("Polo", originalT.echo("Marco"));204 }205 static class UtilClass {206 public static String staticMethod(String str) {207 return str;208 }209 public static void staticVoidMethod(String str) {210 staticMethod(str);211 }212 }213 @Test214 public void testVerifyStaticMethod() {215 MockitoSession session = mockitoSession().spyStatic(UtilClass.class).startMocking();216 try {217 UtilClass.staticVoidMethod("string");218 UtilClass.staticMethod("string");219 verify(() -> UtilClass.staticMethod("string"), atLeastOnce());220 verify(() -> UtilClass.staticMethod("string"), times(2));221 verify(() -> UtilClass.staticVoidMethod("string"), atLeastOnce());222 verify(() -> UtilClass.staticVoidMethod("string"), atMost(2));223 } finally {224 session.finishMocking();225 }226 }227}...
Source:MockitoSession.java
...44 * MockitoSession mockito;45 *46 * @Before public void setup() {47 * //initialize session to start mocking48 * mockito = Mockito.mockitoSession()49 * .initMocks(this)50 * .strictness(Strictness.STRICT_STUBS)51 * .startMocking();52 * }53 *54 * @After public void tearDown() {55 * //It is necessary to finish the session so that Mockito56 * // can detect incorrect stubbing and validate Mockito usage57 * //'finishMocking()' is intended to be used in your test framework's 'tear down' method.58 * mockito.finishMocking();59 * }60 *61 * // test methods ...62 * }...
Source:MockitoSessionTest.java
...77 }78 public static class SessionWithoutAnyConfiguration {79 @Mock IMethods mock;80 //session without initMocks is not currently supported81 MockitoSession mockito = Mockito.mockitoSession().startMocking();82 @After public void after() {83 mockito.finishMocking();84 }85 @Test public void some_test() {86 assertNull(mock); //initMocks() was not used when configuring session87 }88 }89 public static class SessionWithoutInitMocksConfigured {90 @Mock IMethods mock;91 MockitoSession mockito = Mockito.mockitoSession().strictness(Strictness.LENIENT).startMocking();92 @After public void after() {93 mockito.finishMocking();94 }95 @Test public void some_test() {96 assertNull(mock); //initMocks() was not used when configuring session97 }98 }99 public static class SessionWithoutStrictnessConfigured {100 @Mock IMethods mock;101 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();102 @After public void after() {103 mockito.finishMocking();104 }105 @Test public void some_test() {106 assertNotNull(mock);107 }108 }109 public static class SessionWithIncorrectMockitoUsage {110 @Mock IMethods mock;111 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();112 @After public void after() {113 mockito.finishMocking();114 }115 @Test public void unfinished_stubbing() {116 when(mock.simpleMethod());117 }118 }119 public static class SessionWithTestFailureAndIncorrectMockitoUsage {120 @Mock IMethods mock;121 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();122 @After public void after() {123 mockito.finishMocking();124 }125 @Test public void unfinished_stubbing_with_other_failure() {126 when(mock.simpleMethod());127 assertTrue(false);128 }129 }130 public static class SessionWithManuallyInitializedMock {131 @Mock IMethods mock;132 IMethods mock2 = Mockito.mock(IMethods.class, "manual mock");133 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();134 @After public void after() {135 mockito.finishMocking();136 }137 @Test public void manual_mock_preserves_its_settings() {138 assertEquals("mock", mockingDetails(mock).getMockCreationSettings().getMockName().toString());139 assertEquals("manual mock", mockingDetails(mock2).getMockCreationSettings().getMockName().toString());140 }141 }142 public static class SessionWithUpdatedStrictness {143 @Mock IMethods mock;144 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking();145 @After public void after() {146 mockito.finishMocking();147 }148 @Test public void manual_mock_preserves_its_settings() {149 when(mock.simpleMethod(1)).thenReturn("foo");150 //when151 mockito.setStrictness(Strictness.LENIENT);152 //then no exception is thrown, even though the arg is different153 mock.simpleMethod(2);154 }155 }156 public static class SessionWithOverriddenFailure {157 @Mock IMethods mock;158 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking();159 @After public void after() {160 mockito.finishMocking(new RuntimeException("Boo!"));161 }162 @Test public void invalid_mockito_usage() {163 verify(mock);164 }165 }166}...
Source:MockitoSessionBuilder.java
1/*2 * Copyright (c) 2018 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.session;6import org.mockito.Incubating;7import org.mockito.MockitoAnnotations;8import org.mockito.MockitoSession;9import org.mockito.exceptions.misusing.UnfinishedMockingSessionException;10import org.mockito.quality.Strictness;11/**12 * Fluent builder interface for {@code MockitoSession} objects.13 * See the documentation and examples in Javadoc for {@link MockitoSession}.14 *15 * @since 2.7.016 */17@Incubating18public interface MockitoSessionBuilder {19 /**20 * Adds the test class instance for initialization of fields annotated with Mockito annotations21 * like {@link org.mockito.Mock}.22 * When this method is invoked it <strong>does not perform</strong> initialization of mocks on the spot!23 * Only when {@link #startMocking()} is invoked then annotated fields will be initialized.24 * Traditional API to initialize mocks, the {@link MockitoAnnotations#initMocks(Object)} method25 * has limited support for driving cleaner tests because it does not support configuring {@link Strictness}.26 * Want cleaner tests and better productivity?27 * Migrate from {@link MockitoAnnotations#initMocks(Object)}28 * to {@link MockitoSession}!29 * <p>30 * This method may be called multiple times to add multiple, e.g. nested, test class instances.31 * <p>32 * See code sample in {@link MockitoSession}.33 *34 * @param testClassInstance test class instance that contains fields with Mockito annotations to be initialized.35 * Passing {@code null} is permitted but will be ignored.36 * @return the same builder instance for fluent configuration of {@code MockitoSession}.37 * @since 2.7.038 */39 @Incubating40 MockitoSessionBuilder initMocks(Object testClassInstance);41 /**42 * Adds the test class instances for initialization of fields annotated with Mockito annotations43 * like {@link org.mockito.Mock}.44 * <p>45 * In most scenarios, you only need to init mocks on a single test class instance.46 * This method is useful for advanced framework integrations (like JUnit5), when a test uses multiple, e.g. nested, test class instances.47 * <p>48 * This method calls {@link #initMocks(Object)} for each passed test class instance.49 *50 * @param testClassInstances test class instances that contains fields with Mockito annotations to be initialized.51 * Passing {@code null} or an empty array is permitted but will be ignored.52 * @return the same builder instance for fluent configuration of {@code MockitoSession}.53 * @see #initMocks(Object)54 * @since 2.15.055 */56 @Incubating57 MockitoSessionBuilder initMocks(Object... testClassInstances);58 /**59 * Configures the name of the {@code MockitoSession} instance.60 * <p>61 * The name is used to output {@linkplain org.mockito.quality.MockitoHint hints} when62 * {@linkplain MockitoSession#finishMocking() finishing} a session.63 * <p>64 * This method is intended to be used by framework integrations, e.g. JUnit. When building65 * a {@code MockitoSession} for direct use, users are not expected to call it.66 *67 * @param name of {@code MockitoSession} instance.68 * Passing {@code null} is permitted and will make the session use a default value.69 * The current default is the name of the last test class instance passed to70 * {@link #initMocks(Object)} or {@link #initMocks(Object...)}, if available;71 * otherwise, {@code "<Unnamed Session>"} is used.72 *73 * @return the same builder instance for fluent configuration of {@code MockitoSession}.74 * @see org.mockito.quality.MockitoHint75 * @since 2.15.076 */77 @Incubating78 MockitoSessionBuilder name(String name);79 /**80 * Configures strictness of {@code MockitoSession} instance.81 * See examples in {@link MockitoSession}.82 *83 * @param strictness for {@code MockitoSession} instance.84 * Passing {@code null} is permitted and will make the session use a default value.85 * The current default is {@link Strictness#STRICT_STUBS}.86 *87 * @return the same builder instance for fluent configuration of {@code MockitoSession}.88 * @since 2.7.089 */90 @Incubating91 MockitoSessionBuilder strictness(Strictness strictness);92 /**93 * Configures logger used by {@code MockitoSession} for emitting94 * {@linkplain org.mockito.quality.MockitoHint warnings} when finishing the session.95 * <p>96 * Please note that the use of {@linkplain Strictness#STRICT_STUBS strict stubs} is97 * recommended over emitting warnings because warnings are easily ignored and spoil the log output.98 * Instead of using this method, please consider setting strictness with {@link #strictness(Strictness)}.99 *100 * @param logger for warnings emitted when finishing {@code MockitoSession}.101 * Passing {@code null} is permitted and will make the session use a default value.102 * By default, warnings will be logged to the console.103 *104 * @return the same builder instance for fluent configuration of {@code MockitoSession}.105 * @see org.mockito.quality.MockitoHint106 * @since 2.15.0107 */108 @Incubating109 MockitoSessionBuilder logger(MockitoSessionLogger logger);110 /**111 * Starts new mocking session! Creates new {@code MockitoSession} instance to initialize the session.112 * At this point annotated fields are initialized per {@link #initMocks(Object)} method.113 * When you are done with the session it is required to invoke {@link MockitoSession#finishMocking()}.114 * This will trigger stubbing validation, cleaning up the internal state like removal of internal listeners.115 * <p>116 * Mockito tracks created sessions internally and prevents the user from creating new sessions without117 * using {@link MockitoSession#finishMocking()}.118 * When you run tests concurrently in multiple threads, it is legal for each thread to have single active Mockito session.119 * When you attempt to start new session in a thread that already has an unfinished session120 * {@link UnfinishedMockingSessionException} will be triggered.121 * <p>122 * See examples in {@link MockitoSession}.123 *124 * @return new {@code MockitoSession} instance125 * @since 2.7.0126 * @throws UnfinishedMockingSessionException127 * when previous session was not concluded with {@link MockitoSession#finishMocking()}128 */129 @Incubating130 MockitoSession startMocking() throws UnfinishedMockingSessionException;131}...
Source:StrictStubbingEndToEndTest.java
...66 assertThat(results.get(ReportMismatchButNotUnusedStubbing.class)).fails(1);67 }68 public static class UnnecessaryStubbing {69 @Mock IMethods mock;70 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking();71 @After public void after() {72 mockito.finishMocking();73 }74 @Test public void unnecessary_stubbing() {75 given(mock.simpleMethod("1")).willReturn("one");76 throw new IllegalStateException();77 }78 }79 public static class ReportMismatchButNotUnusedStubbing {80 @Mock IMethods mock;81 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking();82 @After public void after() {83 mockito.finishMocking();84 }85 @Test public void mismatch() {86 given(mock.simpleMethod(1)).willReturn("");87 mock.simpleMethod(2);88 }89 }90 public static class StrictStubsPassing {91 @Mock IMethods mock;92 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking();93 @After public void after() {94 mockito.finishMocking();95 }96 @Test public void used() {97 given(mock.simpleMethod(1)).willReturn("");98 mock.simpleMethod(1);99 }100 }101 public static class LenientStrictness1 {102 @Mock IMethods mock = Mockito.mock(IMethods.class);103 @Test public void unused() {104 given(mock.simpleMethod(1)).willReturn("");105 }106 @Test public void mismatch() {107 given(mock.simpleMethod(2)).willReturn("");108 mock.simpleMethod(3);109 }110 }111 public static class LenientStrictness2 {112 @Mock IMethods mock = Mockito.mock(IMethods.class);113 @Test public void unused() {114 given(mock.simpleMethod(1)).willReturn("");115 }116 @Test public void mismatch() {117 given(mock.simpleMethod(2)).willReturn("");118 mock.simpleMethod(3);119 }120 }121 public static class UnfinishedMocking {122 @Mock IMethods mock;123 MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking();124 @Test public void unused() {125 given(mock.simpleMethod("1")).willReturn("one");126 }127 @Test public void unused2() {128 given(mock.simpleMethod("1")).willReturn("one");129 }130 }131}...
Source:JUnitRule.java
...24 return new Statement() {25 public void evaluate() throws Throwable {26 if (JUnitRule.this.session == null) {27 JUnitRule jUnitRule = JUnitRule.this;28 MockitoSessionBuilder mockitoSession = Mockito.mockitoSession();29 MockitoSession unused = jUnitRule.session = mockitoSession.name(obj.getClass().getSimpleName() + "." + frameworkMethod.getName()).strictness(JUnitRule.this.strictness).logger(new MockitoSessionLoggerAdapter(JUnitRule.this.logger)).initMocks(obj).startMocking();30 } else {31 MockitoAnnotations.initMocks(obj);32 }33 Throwable evaluateSafely = evaluateSafely(statement);34 JUnitRule.this.session.finishMocking(evaluateSafely);35 if (evaluateSafely != null) {36 throw evaluateSafely;37 }38 }39 private Throwable evaluateSafely(Statement statement) {40 try {41 statement.evaluate();42 return null;43 } catch (Throwable th) {44 return th;45 }46 }47 };48 }49 public MockitoRule silent() {50 return strictness(Strictness.LENIENT);51 }52 public MockitoRule strictness(Strictness strictness2) {53 this.strictness = strictness2;54 MockitoSession mockitoSession = this.session;55 if (mockitoSession != null) {56 mockitoSession.setStrictness(strictness2);57 }58 return this;59 }60}...
Source:MockitoSessionTestBase.java
...8 * Makes it easier to use {@linkplain MockitoSession} (recommended by Mockito team)9 * in favour of, say, recently deprecated {@linkplain org.mockito.MockitoAnnotations#initMocks}.10 */11public class MockitoSessionTestBase {12 private MockitoSession mockitoSession;13 @Before14 public void initMocks() {15 mockitoSession = Mockito.mockitoSession()16 .initMocks(this)17 .strictness(Strictness.WARN)18 .startMocking();19 }20 @After21 public void releaseMocks() throws Exception {22 mockitoSession.finishMocking();23 }24}...
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoSession;3import org.mockito.quality.Strictness;4public class MockitoSessionExample {5 public static void main(String[] args) {6 MockitoSession mockitoSession = Mockito.mockitoSession()7 .initMocks(new Object() {8 private List<String> mockList;9 })10 .strictness(Strictness.STRICT_STUBS)11 .startMocking();12 mockitoSession.finishMocking();13 }14}15 MockitoSession mockitoSession = Mockito.mockitoSession()16 symbol: method mockitoSession()
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoSession;3import org.mockito.quality.Strictness;4public class 1 {5 public static void main(String[] args) {6 MockitoSession mockitoSession = Mockito.mockitoSession().initMocks(new Object()).strictness(Strictness.STRICT_STUBS).startMocking();7 }8}9 at org.mockito.internal.session.MockitoSessionImpl.initMocks(MockitoSessionImpl.java:66)10 at org.mockito.MockitoSessionBuilder.initMocks(MockitoSessionBuilder.java:50)11 at 1.main(1.java:7)
mockitoSession
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mock;3import org.mockito.Mockito;4import org.mockito.MockitoSession;5import org.mockito.quality.Strictness;6import org.mockito.stubbing.Answer;7import org.mockito.invocation.InvocationOnMock;8import org.mockito.stubbing.Stubber;9import org.mockito.stubbing.OngoingStubbing;10import org.mockito.stubbing.VoidMethodStubber;11import org.mockito.stubbing.Stubber;12import org.mockito.stubbing.Answer;13import org.mockito.invocation.InvocationOnMock;14import org.mockito.stubbing.OngoingStubbing;15import org.mockito.stubbing.VoidMethodStubber;16import org.mockito.stubbing.Stubber;17import org.mockito.stubbing.Answer;18import org.mockito.invocation.InvocationOnMock;19import org.mockito.stubbing.OngoingStubbing;20import org.mockito.stubbing.VoidMethodStubber;21import org.mockito.stubbing.Stubber;22import org.mockito.stubbing.Answer;23import org.mockito.invocation.InvocationOnMock;24import org.mockito.stubbing.OngoingStubbing;25import org.mockito.stubbing.VoidMethodStubber;26import org.mockito.stubbing.Stubber;27import org.mockito.stubbing.Answer;28import org.mockito.invocation.InvocationOnMock;29import org.mockito.stubbing.OngoingStubbing;30import org.mockito.stubbing.VoidMethodStubber;31import org.mockito.stubbing.Stubber;32import org.mockito.stubbing.Answer;33import org.mockito.invocation.InvocationOnMock;34import org.mockito.stubbing.OngoingStubbing;35import org.mockito.stubbing.VoidMethodStubber;36import org.mockito.stubbing.Stubber;37import org.mockito.stubbing.Answer;38import org.mockito.invocation.InvocationOnMock;39import org.mockito.stubbing.OngoingStubbing;40import org.mockito.stubbing.VoidMethodStubber;41import org.mockito.stubbing.Stubber;42import org.mockito.stubbing.Answer;43import org.mockito.invocation.InvocationOnMock;44import org.mockito.stubbing.OngoingStubbing;45import org.mockito.stubbing.VoidMethodStubber;46import org.mockito.stubbing.Stubber;47import org.mockito.stubbing.Answer;48import org.mockito.invocation.InvocationOnMock;49import org.mockito.stubbing.OngoingStubbing;50import org.mockito.stubbing.VoidMethodStubber;51import org.mockito.stubbing.Stubber;52import org.mockito.stubbing.Answer;53import org.mockito.invocation.InvocationOnMock;54import org.mockito.stubbing.OngoingStubbing;55import org.mockito.stubbing.VoidMethodStubber;56import org.mockito.stubbing.Stubber;
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoSession;3import org.mockito.quality.Strictness;4public class MockSession {5 public static void main(String[] args) {6 MockitoSession mockitoSession = Mockito.mockitoSession()7 .initMocks(this)8 .strictness(Strictness.STRICT_STUBS)9 .mockStatic(Strictness.class)10 .startMocking();11 }12}
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoSession;3import org.mockito.quality.Strictness;4public class 1 {5public static void main(String[] args) {6MockitoSession mockitoSession = Mockito.mockitoSession().initMocks(new Object() {7}).strictness(Strictness.STRICT_STUBS).startMocking();8}9}10import org.mockito.Mockito;11import org.mockito.MockitoSession;12import org.mockito.quality.Strictness;13public class 1 {14public static void main(String[] args) {15MockitoSession mockitoSession = Mockito.mockitoSession().initMocks(new Object() {16}).strictness(Strictness.STRICT_STUBS).startMocking();17}18}19import org.mockito.Mockito;20import org.mockito.MockitoSession;21import org.mockito.quality.Strictness;22public class 1 {23public static void main(String[] args) {24MockitoSession mockitoSession = Mockito.mockitoSession().initMocks(new Object() {25}).strictness(Strictness.STRICT_STUBS).startMocking();26}27}
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoSession;3import org.mockito.quality.Strictness;4public class MockitoSessionExample {5 public static void main(String[] args) {6 MockitoSession mockitoSession = Mockito.mockitoSession()7 .initMocks(this)8 .strictness(Strictness.LENIENT)9 .startMocking();10 mockitoSession.finishMocking();11 }12}13It is not possible to create a mockito session without using the mockitoSession() method of the Mockito class. The method returns a MockitoSession object which is used to create a mockito session. The MockitoSession class provides the following methods:
mockitoSession
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.quality.Strictness;3public class MockitoSessionExample {4 public static void main(String[] args) {5 Mockito.mockingDetails(Mockito.mock(MockitoSessionExample.class));6 Mockito.mockingDetails(Mockito.mock(MockitoSessionExample.class));7 Mockito.mockingDetails(Mockito.mock(MockitoSessionExample.class));8 MockitoSessionExample example = Mockito.mock(MockitoSessionExample.class);9 Mockito.mockingDetails(e
mockitoSession
Using AI Code Generation
1package com.acktutorial.mockitotest;2import org.junit.Test;3import org.mockito.Mockito;4public class MockitoTest {5 public void testMockitoSession() {6 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();7 }8}9package com.acktutorial.mockitotest;10import org.junit.Test;11import org.mockito.Mockito;12public class MockitoTest2 {13 public void testMockitoSession() {14 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();15 }16}17package com.acktutorial.mockitotest;18import org.junit.Test;19import org.mockito.Mockito;20public class MockitoTest3 {21 public void testMockitoSession() {22 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();23 }24}25package com.acktutorial.mockitotest;26import org.junit.Test;27import org.mockito.Mockito;28public class MockitoTest4 {29 public void testMockitoSession() {30 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();31 }32}33package com.acktutorial.mockitotest;34import org.junit.Test;35import org.mockito.Mockito;36public class MockitoTest5 {37 public void testMockitoSession() {38 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();39 }40}41package com.acktutorial.mockitotest;42import org.junit.Test;43import org.mockito.Mockito;44public class MockitoTest6 {45 public void testMockitoSession() {46 Mockito.mockingDetails(Mockito.mock(Runnable.class)).getMockCreationSettings().getMockName();47 }48}
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!!