Best Mockito code snippet using org.mockito.internal.verification.VerificationModeFactory.VerificationModeFactory
Source:ErrorHandlingExecutionTemplateTestCase.java
...37import org.junit.runner.RunWith;38import org.mockito.Answers;39import org.mockito.Mock;40import org.mockito.Spy;41import org.mockito.internal.verification.VerificationModeFactory;42import org.mockito.invocation.InvocationOnMock;43import org.mockito.runners.MockitoJUnitRunner;44import org.mockito.stubbing.Answer;45@RunWith(MockitoJUnitRunner.class)46@SmallTest47public class ErrorHandlingExecutionTemplateTestCase extends AbstractMuleTestCase48{49 private MuleContext mockMuleContext = mock(MuleContext.class, RETURNS_DEEP_STUBS);50 @Mock51 private MuleEvent RETURN_VALUE;52 @Mock53 private MessagingException mockMessagingException;54 @Mock(answer = Answers.RETURNS_DEEP_STUBS)55 private MuleEvent mockEvent;56 @Spy57 protected TestTransaction mockTransaction = new TestTransaction(mockMuleContext);58 @Mock59 protected MessagingExceptionHandler mockMessagingExceptionHandler;60 @Before61 public void unbindTransaction() throws Exception62 {63 Transaction currentTransaction = TransactionCoordination.getInstance().getTransaction();64 if (currentTransaction != null)65 {66 TransactionCoordination.getInstance().unbindTransaction(currentTransaction);67 }68 when(mockMessagingException.getStackTrace()).thenReturn(new StackTraceElement[0]);69 }70 @Test71 public void testSuccessfulExecution() throws Exception72 {73 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();74 Object result = executionTemplate.execute(getEmptyTransactionCallback(RETURN_VALUE));75 assertThat((MuleEvent) result, is(RETURN_VALUE));76 }77 private ExecutionTemplate createExceptionHandlingTransactionTemplate()78 {79 return ErrorHandlingExecutionTemplate.createErrorHandlingExecutionTemplate(mockMuleContext, mockMessagingExceptionHandler);80 }81 @Test82 public void testFailureException() throws Exception83 {84 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();85 MuleEvent mockResultEvent = mock(MuleEvent.class);86 when(mockMessagingException.getEvent()).thenReturn(mockEvent).thenReturn(mockEvent).thenReturn(mockResultEvent);87 when(mockMessagingExceptionHandler.handleException(mockMessagingException, mockEvent)).thenReturn(mockResultEvent);88 try89 {90 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));91 fail("MessagingException must be thrown");92 }93 catch (MessagingException e)94 {95 assertThat(e, Is.is(mockMessagingException));96 verify(mockMessagingException).setProcessedEvent(mockResultEvent);97 }98 }99 @Test100 public void testTransactionIsMarkedRollbackOnExceptionByDefault() throws Exception101 {102 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();103 TransactionCoordination.getInstance().bindTransaction(mockTransaction);104 configureExceptionListener(null,null);105 try106 {107 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));108 fail("MessagingException must be thrown");109 }110 catch (MessagingException e) {}111 verify(mockTransaction).rollback();112 }113 @Test114 public void testTransactionIsNotRollbackOnEveryException() throws Exception115 {116 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();117 TransactionCoordination.getInstance().bindTransaction(mockTransaction);118 configureExceptionListener(null, "*");119 try120 {121 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));122 fail("MessagingException must be thrown");123 }124 catch (MessagingException e) {}125 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();126 verify(mockTransaction, VerificationModeFactory.times(0)).commit();127 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();128 }129 @Test130 public void testTransactionIsNotRollbackOnMatcherRegexPatternException() throws Exception131 {132 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();133 TransactionCoordination.getInstance().bindTransaction(mockTransaction);134 configureExceptionListener(null, "org.mule.ap*");135 try136 {137 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));138 fail("MessagingException must be thrown");139 }140 catch (MessagingException e) {}141 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();142 verify(mockTransaction, VerificationModeFactory.times(0)).commit();143 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();144 }145 @Test146 public void testTransactionIsNotRollbackOnClassHierarchyPatternException() throws Exception147 {148 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();149 TransactionCoordination.getInstance().bindTransaction(mockTransaction);150 configureExceptionListener(null, "org.mule.api.MuleException+");151 try152 {153 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));154 fail("MessagingException must be thrown");155 }156 catch (MessagingException e) {}157 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();158 verify(mockTransaction, VerificationModeFactory.times(0)).commit();159 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();160 }161 @Test162 public void testTransactionIsNotRollbackOnClassExactlyPatternException() throws Exception163 {164 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();165 TransactionCoordination.getInstance().bindTransaction(mockTransaction);166 configureExceptionListener(null, "org.mule.api.MessagingException");167 try168 {169 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(new MessagingException(mockEvent, null)));170 fail("MessagingException must be thrown");171 }172 catch (MessagingException e) {}173 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();174 verify(mockTransaction, VerificationModeFactory.times(0)).commit();175 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();176 }177 @Test178 public void testTransactionIsRollbackOnPatternAppliesToRollbackAndCommit() throws Exception179 {180 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();181 TransactionCoordination.getInstance().bindTransaction(mockTransaction);182 configureExceptionListener("org.mule.api.MuleException+", "org.mule.api.MessagingException");183 try184 {185 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));186 fail("MessagingException must be thrown");187 }188 catch (MessagingException e) {}189 verify(mockTransaction, VerificationModeFactory.times(1)).setRollbackOnly();190 verify(mockTransaction, VerificationModeFactory.times(0)).commit();191 verify(mockTransaction, VerificationModeFactory.times(1)).rollback();192 }193 @Test194 public void testSuspendedTransactionNotResumedOnException() throws Exception195 {196 mockTransaction.setXA(true);197 TransactionCoordination.getInstance().bindTransaction(mockTransaction);198 TransactionCoordination.getInstance().suspendCurrentTransaction();199 assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.<Object>nullValue());200 configureExceptionListener(null,null);201 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();202 try203 {204 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallback(mockMessagingException));205 fail("MessagingException must be thrown");206 }207 catch (MessagingException e) {}208 verify(mockTransaction, VerificationModeFactory.times(0)).resume();209 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();210 verify(mockTransaction, VerificationModeFactory.times(0)).commit();211 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();212 assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.<Object>nullValue());213 }214 @Test215 public void testSuspendedTransactionNotResumedAndNewTransactionResolvedOnException() throws Exception216 {217 mockTransaction.setXA(true);218 TransactionCoordination.getInstance().bindTransaction(mockTransaction);219 TransactionCoordination.getInstance().suspendCurrentTransaction();220 assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.<Object>nullValue());221 configureExceptionListener(null,null);222 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();223 final Transaction mockNewTransaction = spy(new TestTransaction(mockMuleContext));224 try225 {226 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallbackStartsTransaction(mockMessagingException, mockNewTransaction));227 fail("MessagingException must be thrown");228 }229 catch (MessagingException e) {}230 verify(mockTransaction, VerificationModeFactory.times(0)).resume();231 verify(mockTransaction, VerificationModeFactory.times(0)).rollback();232 verify(mockTransaction, VerificationModeFactory.times(0)).commit();233 verify(mockTransaction, VerificationModeFactory.times(0)).setRollbackOnly();234 verify(mockNewTransaction, VerificationModeFactory.times(1)).rollback();235 verify(mockNewTransaction, VerificationModeFactory.times(0)).commit();236 verify(mockNewTransaction, VerificationModeFactory.times(1)).setRollbackOnly();237 assertThat(TransactionCoordination.getInstance().getTransaction(),IsNull.<Object>nullValue());238 }239 @Test240 public void testTransactionIsResolved() throws Exception241 {242 configureExceptionListener(null,null);243 ExecutionTemplate executionTemplate = createExceptionHandlingTransactionTemplate();244 try245 {246 executionTemplate.execute(TransactionTemplateTestUtils.getFailureTransactionCallbackStartsTransaction(mockMessagingException, mockTransaction));247 fail("MessagingException must be thrown");248 }249 catch (MessagingException e) {}250 verify(mockTransaction, VerificationModeFactory.times(1)).setRollbackOnly();251 verify(mockTransaction, VerificationModeFactory.times(1)).rollback();252 verify(mockTransaction, VerificationModeFactory.times(0)).commit();253 assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.<Object>nullValue());254 }255 private void configureExceptionListener(final String rollbackFilter,final String commitFilter)256 {257 when(mockMessagingException.getEvent()).thenReturn(mockEvent);258 when(mockMuleContext.getNotificationManager()).thenReturn(mock(ServerNotificationManager.class));259 when(mockMuleContext.getRegistry()).thenReturn(mock(MuleRegistry.class));260 when(mockMessagingExceptionHandler.handleException(any(MessagingException.class), any(MuleEvent.class))).thenAnswer(new Answer<Object>()261 {262 @Override263 public Object answer(InvocationOnMock invocationOnMock) throws Throwable264 {265 DefaultMessagingExceptionStrategy defaultMessagingExceptionStrategy = new DefaultMessagingExceptionStrategy();266 defaultMessagingExceptionStrategy.setMuleContext(mockMuleContext);...
Source:Mockito.java
2import org.mockito.internal.MockitoCore;3import org.mockito.internal.creation.MockSettingsImpl;4import org.mockito.internal.framework.DefaultMockitoFramework;5import org.mockito.internal.session.DefaultMockitoSessionBuilder;6import org.mockito.internal.verification.VerificationModeFactory;7import org.mockito.session.MockitoSessionBuilder;8import org.mockito.stubbing.Answer;9import org.mockito.stubbing.OngoingStubbing;10import org.mockito.stubbing.Stubber;11import org.mockito.verification.After;12import org.mockito.verification.Timeout;13import org.mockito.verification.VerificationAfterDelay;14import org.mockito.verification.VerificationMode;15import org.mockito.verification.VerificationWithTimeout;16import java.security.AccessController;17import java.security.PrivilegedAction;18/**19 * Wraps Mockito API with calls to AccessController.20 * This is useful if you want to mock in a SecurityManager environment,21 * but contain the permissions to only mocking test libraries.22 * <p>23 * Instead of:24 * <pre>25 * grant {26 * permission java.lang.RuntimePermission "reflectionFactoryAccess";27 * };28 * </pre>29 * You can just change maven dependencies to use securemock.jar, and then:30 * <pre>31 * grant codeBase "/url/to/securemock.jar" {32 * permission java.lang.RuntimePermission "reflectionFactoryAccess";33 * };34 * </pre>35 */36@SuppressWarnings("unchecked")37public class Mockito extends ArgumentMatchers {38 static final MockitoCore MOCKITO_CORE = new MockitoCore();39 public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;40 public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;41 public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;42 public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;43 public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;44 public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;45 public static <T> T mock(Class<T> classToMock) {46 T mockedClass = AccessController.doPrivileged((PrivilegedAction<T>) () ->47 mock(classToMock, withSettings()));48 if (mockedClass == null) {49 throw new IllegalStateException("unable to mock " + classToMock);50 }51 return mockedClass;52 }53 public static <T> T mock(final Class<T> classToMock, final String name) {54 return AccessController.doPrivileged((PrivilegedAction<T>) () ->55 mock(classToMock, withSettings()56 .name(name)57 .defaultAnswer(RETURNS_DEFAULTS)));58 }59 60 public static MockingDetails mockingDetails(final Object toInspect) {61 return AccessController.doPrivileged((PrivilegedAction<MockingDetails>) () ->62 MOCKITO_CORE.mockingDetails(toInspect));63 }64 public static <T> T mock(final Class<T> classToMock, final Answer defaultAnswer) {65 return AccessController.doPrivileged((PrivilegedAction<T>) () ->66 mock(classToMock, withSettings().defaultAnswer(defaultAnswer)));67 }68 69 public static <T> T mock(final Class<T> classToMock, final MockSettings mockSettings) {70 return AccessController.doPrivileged((PrivilegedAction<T>) () ->71 MOCKITO_CORE.mock(classToMock, mockSettings));72 }73 74 public static <T> T spy(final T object) {75 return AccessController.doPrivileged((PrivilegedAction<T>) () ->76 MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()77 .spiedInstance(object)78 .defaultAnswer(CALLS_REAL_METHODS)));79 }80 public static <T> T spy(Class<T> classToSpy) {81 return AccessController.doPrivileged((PrivilegedAction<T>) () ->82 MOCKITO_CORE.mock(classToSpy, withSettings()83 .useConstructor()84 .defaultAnswer(CALLS_REAL_METHODS)));85 }86 public static <T> OngoingStubbing<T> when(final T methodCall) {87 return AccessController.doPrivileged((PrivilegedAction<OngoingStubbing<T>>) () ->88 MOCKITO_CORE.when(methodCall));89 }90 91 public static <T> T verify(final T mock) {92 return AccessController.doPrivileged((PrivilegedAction<T>) () ->93 MOCKITO_CORE.verify(mock, times(1)));94 }95 96 public static <T> T verify(final T mock, final VerificationMode mode) {97 return AccessController.doPrivileged((PrivilegedAction<T>) () ->98 MOCKITO_CORE.verify(mock, mode));99 }100 101 public static <T> void reset(final T ... mocks) {102 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {103 MOCKITO_CORE.reset(mocks);104 return null;105 });106 }107 public static <T> void clearInvocations(T ... mocks) {108 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {109 MOCKITO_CORE.clearInvocations(mocks);110 return null;111 });112 }113 public static void verifyNoMoreInteractions(final Object... mocks) {114 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {115 MOCKITO_CORE.verifyNoMoreInteractions(mocks);116 return null;117 });118 }119 120 public static void verifyZeroInteractions(final Object... mocks) {121 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {122 MOCKITO_CORE.verifyNoMoreInteractions(mocks);123 return null;124 });125 }126 127 public static Stubber doThrow(final Throwable... toBeThrown) {128 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->129 MOCKITO_CORE.stubber().doThrow(toBeThrown));130 }131 132 public static Stubber doThrow(final Class<? extends Throwable> toBeThrown) {133 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->134 MOCKITO_CORE.stubber().doThrow(toBeThrown));135 }136 public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {137 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->138 MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext));139 }140 public static Stubber doCallRealMethod() {141 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->142 MOCKITO_CORE.stubber().doCallRealMethod());143 }144 145 public static Stubber doAnswer(final Answer answer) {146 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->147 MOCKITO_CORE.stubber().doAnswer(answer));148 } 149 150 public static Stubber doNothing() {151 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->152 MOCKITO_CORE.stubber().doNothing());153 }154 155 public static Stubber doReturn(final Object toBeReturned) {156 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->157 MOCKITO_CORE.stubber().doReturn(toBeReturned));158 }159 public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {160 return AccessController.doPrivileged((PrivilegedAction<Stubber>) () ->161 MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext));162 }163 164 public static InOrder inOrder(final Object... mocks) {165 return AccessController.doPrivileged((PrivilegedAction<InOrder>) () ->166 MOCKITO_CORE.inOrder(mocks));167 }168 169 public static Object[] ignoreStubs(final Object... mocks) {170 return AccessController.doPrivileged((PrivilegedAction<Object[]>) () ->171 MOCKITO_CORE.ignoreStubs(mocks));172 }173 174 public static VerificationMode times(final int wantedNumberOfInvocations) {175 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>) () ->176 VerificationModeFactory.times(wantedNumberOfInvocations));177 }178 179 public static VerificationMode never() {180 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>) () ->181 times(0));182 }183 184 public static VerificationMode atLeastOnce() {185 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>)186 VerificationModeFactory.atLeastOnce());187 }188 189 public static VerificationMode atLeast(final int minNumberOfInvocations) {190 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>) () ->191 VerificationModeFactory.atLeast(minNumberOfInvocations));192 }193 194 public static VerificationMode atMost(final int maxNumberOfInvocations) {195 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>) () ->196 VerificationModeFactory.atMost(maxNumberOfInvocations));197 }198 199 public static VerificationMode calls(final int wantedNumberOfInvocations) {200 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>) () ->201 VerificationModeFactory.calls(wantedNumberOfInvocations));202 }203 204 public static VerificationMode only() {205 return AccessController.doPrivileged((PrivilegedAction<VerificationMode>)206 VerificationModeFactory::only);207 }208 209 public static VerificationWithTimeout timeout(final int millis) {210 return AccessController.doPrivileged((PrivilegedAction<VerificationWithTimeout>) () ->211 new Timeout(millis, VerificationModeFactory.times(1)));212 }213 public static VerificationAfterDelay after(long millis) {214 return AccessController.doPrivileged((PrivilegedAction<VerificationAfterDelay>) () ->215 new After(millis, VerificationModeFactory.times(1)));216 }217 218 public static void validateMockitoUsage() {219 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {220 MOCKITO_CORE.validateMockitoUsage();221 return null;222 });223 }224 225 public static MockSettings withSettings() {226 return AccessController.doPrivileged((PrivilegedAction<MockSettings>) () ->227 new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS));228 }229 public static VerificationMode description(String description) {...
Source:CityService_UnitTest.java
...4import org.junit.jupiter.api.extension.ExtendWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.Mockito;8import org.mockito.internal.verification.VerificationModeFactory;9import org.mockito.junit.jupiter.MockitoExtension;10import tqsua.midterm_assignment.cache.Cache;11import tqsua.midterm_assignment.external_api.ExternalAPI;12import static org.assertj.core.api.AssertionsForClassTypes.assertThat;13@ExtendWith(MockitoExtension.class)14class CityService_UnitTest {15 @Mock(lenient = true)16 private Cache cache;17 @Mock(lenient = true)18 private ExternalAPI api;19 @InjectMocks20 private CityService service;21 @BeforeEach22 public void setUp() {23 Mockito.when(cache.getStates("USA")).thenReturn(new String[]{"Alaska", "Kansas"});24 Mockito.when(api.getStates("USA")).thenReturn(new String[]{"Alaska", "Kansas"});25 Mockito.when(cache.getStates("France")).thenReturn(new String[0]);26 Mockito.when(api.getStates("France")).thenReturn(new String[]{"Brittany", "Burgundy"});27 Mockito.when(cache.getCities("USA", "Alaska")).thenReturn(new String[]{"City1", "City2"});28 Mockito.when(api.getCities("USA", "Alaska")).thenReturn(new String[]{"City1", "City2"});29 Mockito.when(cache.getCities("France", "Brittany")).thenReturn(new String[0]);30 Mockito.when(api.getCities("France", "Brittany")).thenReturn(new String[]{"City1", "City2"});31 Mockito.when(cache.getStates("NotReal")).thenReturn(new String[0]);32 Mockito.when(api.getStates("NotReal")).thenReturn(new String[0]);33 Mockito.when(cache.getCities("NotReal","A")).thenReturn(new String[0]);34 Mockito.when(api.getCities("NotReal", "A")).thenReturn(new String[0]);35 }36 @Test37 void whenCountriesExistInCache_thenTheyShouldBeFoundOnTheCache() {38 String[] countries = new String[]{"USA", "France"};39 Mockito.when(cache.getCountries()).thenReturn(countries);40 Mockito.when(api.getCountries()).thenReturn(countries);41 String[] found = service.getCountries();42 assertThat(found).hasSize(2).contains("USA", "France");43 Mockito.verify(cache, VerificationModeFactory.times(1)).getCountries();44 Mockito.verify(api, VerificationModeFactory.times(0)).getCountries();45 }46 @Test47 void whenCountriesExistOnlyInExternalAPI_thenTheyShouldBeFoundOnTheAPI() {48 String[] countries = new String[]{"USA", "France"};49 Mockito.when(cache.getCountries()).thenReturn(new String[0]);50 Mockito.when(api.getCountries()).thenReturn(countries);51 String[] found = service.getCountries();52 assertThat(found).hasSize(2).contains("USA", "France");53 Mockito.verify(cache, VerificationModeFactory.times(1)).getCountries();54 Mockito.verify(api, VerificationModeFactory.times(1)).getCountries();55 }56 @Test57 void whenStatesExistInCache_thenTheyShouldBeFoundOnTheCache() {58 String[] found = service.getStates("USA");59 assertThat(found).hasSize(2).contains("Alaska", "Kansas");60 Mockito.verify(cache, VerificationModeFactory.times(1)).getStates("USA");61 Mockito.verify(api, VerificationModeFactory.times(0)).getStates("USA");62 }63 @Test64 void whenStatesExistOnlyInExternalAPI_thenTheyShouldBeFoundOnTheAPI() {65 String[] found = service.getStates("France");66 assertThat(found).hasSize(2).contains("Burgundy", "Brittany");67 Mockito.verify(cache, VerificationModeFactory.times(1)).getStates("France");68 Mockito.verify(api, VerificationModeFactory.times(1)).getStates("France");69 }70 @Test71 void whenCitiesExistInCache_thenTheyShouldBeFoundOnTheCache() {72 String[] found = service.getCities("USA", "Alaska");73 assertThat(found).hasSize(2).contains("City1", "City2");74 Mockito.verify(cache, VerificationModeFactory.times(1)).getCities("USA", "Alaska");75 Mockito.verify(api, VerificationModeFactory.times(0)).getCities("USA", "Alaska");76 }77 @Test78 void whenCitiesExistOnlyInExternalAPI_thenTheyShouldBeFoundOnTheAPI() {79 String[] found = service.getCities("France", "Brittany");80 assertThat(found).hasSize(2).contains("City1", "City2");81 Mockito.verify(cache, VerificationModeFactory.times(1)).getCities("France", "Brittany");82 Mockito.verify(api, VerificationModeFactory.times(1)).getCities("France", "Brittany");83 }84 @Test85 void whenCountryDoesNotExist_thenStatesShouldNotBeFound() {86 String[] found = service.getStates("NotReal");87 assertThat(found).isEmpty();88 Mockito.verify(cache, VerificationModeFactory.times(1)).getStates("NotReal");89 Mockito.verify(api, VerificationModeFactory.times(1)).getStates("NotReal");90 }91 @Test92 void whenStateOrCountryDoesNotExist_thenCitiesShouldNotBeFound() {93 String[] found = service.getCities("NotReal", "A");94 assertThat(found).isEmpty();95 Mockito.verify(cache, VerificationModeFactory.times(1)).getCities("NotReal", "A");96 Mockito.verify(api, VerificationModeFactory.times(1)).getCities("NotReal", "A");97 }98}...
Source:AQService_WithMock.java
...4import org.junit.jupiter.api.extension.ExtendWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.Mockito;8import org.mockito.internal.verification.VerificationModeFactory;9import org.mockito.junit.jupiter.MockitoExtension;10import org.springframework.web.client.RestTemplate;11import tqs.assignment.component.Cache;12import tqs.assignment.entity.City;13import tqs.assignment.entity.AirQResponse;14import tqs.assignment.service.impl.AirQualityServiceImpl;15import java.util.*;16import static org.junit.jupiter.api.Assertions.*;17import static org.mockito.ArgumentMatchers.*;18import static org.mockito.Mockito.verify;19/**20 * @author wy21 * @date 2021/4/28 10:3422 */23@ExtendWith(MockitoExtension.class)24public class AQService_WithMock {25 private static final String URL = "https://api.waqi.info/feed/";26 private static final String JOIN_STR = "?token=";27 private static final String TOKEN = "6934d1d173fc8dd18ee0f5e2be89497fd7e1995f";28 @Mock(lenient = true)29 private Cache cache;30 @Mock(lenient = true)31 private RestTemplate restTemplate;32 @InjectMocks33 private AirQualityServiceImpl service;34 private AirQResponse airQResponse;35 @BeforeEach36 public void setUp() {37 String location = "Aveiro";38 airQResponse = new AirQResponse();39 City city = new City();40 city.setName(location);41 airQResponse.setCity(city);42 airQResponse.setDominentpol("pm3");43 airQResponse.setIaqis(Map.of("pm1", 10, "pm2", 11, "pm3", 12));44 // when get Aveiro's air quality, service will find Aveiro's air info in cache45 Mockito.when(cache.get(location)).thenReturn(airQResponse);46 // when get Porto's air quality, service should parse a Map object and build a response47 String url = getUrl("porto");48 Map<String, Object> portoMap = new HashMap<>();49 portoMap.put("status", "success");50 portoMap.put("data", Map.of("city", Map.of("name", "porto")));51 Mockito.when(restTemplate52 .getForObject(url, Map.class)).thenReturn(portoMap);53 url = getUrl("invalid");54 Map<String, Object> invalidMap = new HashMap<>();55 invalidMap.put("status", "error");56 invalidMap.put("another", new LinkedHashMap<>());57 Mockito.when(restTemplate58 .getForObject(url, Map.class)).thenReturn(invalidMap);59 }60 @Test61 void givenAveiro_fromCache() {62 AirQResponse aveiro = service.getAirQualityByLocation("Aveiro");63 assertEquals("Aveiro", aveiro.getCity().getName());64 assertEquals("pm3", aveiro.getDominentpol());65 assertEquals(12, aveiro.getIaqis().get("pm3"));66 verify(cache, VerificationModeFactory.times(1)).get("Aveiro");67 verify(cache, VerificationModeFactory.times(0)).put(anyString(), any());68 }69 @Test70 void givenValidCity_thenIsPutInCache() {71 AirQResponse porto = service.getAirQualityByLocation("porto");72 assertEquals("porto", porto.getCity().getName());73 assertNull(porto.getForecasts());74 assertNull(porto.getIaqis());75 verify(cache, VerificationModeFactory.times(1)).get("porto");76 verify(cache, VerificationModeFactory.times(1)).put("porto", porto);77 }78 @Test79 void givenInvalidCity_thenReturnNull() {80 String url = "invalid";81 AirQResponse response = service.getAirQualityByLocation(url);82 assertNull(response);83 verify(cache, VerificationModeFactory.times(1)).get(url);84 verify(cache, VerificationModeFactory.times(1)).put(url, null);85 }86 private String getUrl(String city){87 return URL + city + "/" + JOIN_STR + TOKEN;88 }89}...
Source:AirQualityService_UnitTest.java
...4import org.junit.jupiter.api.extension.ExtendWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.Mockito;8import org.mockito.internal.verification.VerificationModeFactory;9import org.mockito.junit.jupiter.MockitoExtension;10import tqsua.midterm_assignment.cache.Cache;11import tqsua.midterm_assignment.external_api.ExternalAPI;12import tqsua.midterm_assignment.model.AirQuality;13import static org.assertj.core.api.AssertionsForClassTypes.assertThat;14@ExtendWith(MockitoExtension.class)15class AirQualityService_UnitTest {16 @Mock(lenient = true)17 private Cache cache;18 @Mock(lenient = true)19 private ExternalAPI api;20 @InjectMocks21 private AirQualityService service;22 @BeforeEach23 void setUp() {24 AirQuality aq = new AirQuality(30,40,41,"p1","p2");25 Mockito.when(cache.getAirQuality("France", "Brittany", "Quimper")).thenReturn(aq);26 Mockito.when(api.getAirQuality("France", "Brittany", "Quimper")).thenReturn(aq);27 Mockito.when(cache.getAirQuality("France", "Burgundy", "Burgundy")).thenReturn(null);28 Mockito.when(api.getAirQuality("France", "Burgundy", "Burgundy")).thenReturn(aq);29 Mockito.when(cache.getAirQuality("USA", "Alaska", "City1")).thenReturn(null);30 Mockito.when(api.getAirQuality("USA", "Alaska", "City1")).thenReturn(null);31 Mockito.when(cache.getCount()).thenReturn(3);32 Mockito.when(cache.getMisses()).thenReturn(2);33 Mockito.when(cache.getHits()).thenReturn(1);34 }35 @Test36 void whenAirQualityExistsInCache_thenItShouldBeFoundOnTheCache() {37 AirQuality found = service.getAirQualityByCity("France", "Brittany", "Quimper");38 assertThat(found.getHumidity()).isEqualTo(30);39 Mockito.verify(cache, VerificationModeFactory.times(1)).getAirQuality("France", "Brittany", "Quimper");40 Mockito.verify(api, VerificationModeFactory.times(0)).getAirQuality("France", "Brittany", "Quimper");41 }42 @Test43 void whenAirQualityExistsOnlyInExternalAPI_thenItShouldBeFoundOnTheAPI() {44 AirQuality found = service.getAirQualityByCity("France", "Burgundy", "Burgundy");45 assertThat(found.getHumidity()).isEqualTo(30);46 Mockito.verify(cache, VerificationModeFactory.times(1)).getAirQuality("France", "Burgundy", "Burgundy");47 Mockito.verify(api, VerificationModeFactory.times(1)).getAirQuality("France", "Burgundy", "Burgundy");48 }49 @Test50 void whenAirQualityDoesNotExist_thenItShouldNotBeFound() {51 AirQuality found = service.getAirQualityByCity("USA","Alaska", "City1");52 assertThat(found).isNull();53 Mockito.verify(cache, VerificationModeFactory.times(1)).getAirQuality("USA", "Alaska", "City1");54 Mockito.verify(api, VerificationModeFactory.times(1)).getAirQuality("USA", "Alaska", "City1");55 }56 @Test57 void whenGettingStatistics_thenItShouldReturnStatistics() {58 assertThat(service.getStatistics()).hasFieldOrPropertyWithValue("count", 3);59 assertThat(service.getStatistics()).hasFieldOrPropertyWithValue("misses", 2);60 assertThat(service.getStatistics()).hasFieldOrPropertyWithValue("hits", 1);61 Mockito.verify(cache, VerificationModeFactory.times(3)).getCount();62 Mockito.verify(cache, VerificationModeFactory.times(3)).getMisses();63 Mockito.verify(cache, VerificationModeFactory.times(3)).getHits();64 }65}...
Source:CityServiceTest.java
...11import org.junit.Test;12import org.junit.runner.RunWith;13import org.mockito.Mock;14import org.mockito.Mockito;15import org.mockito.internal.verification.VerificationModeFactory;16import org.mockito.runners.MockitoJUnitRunner;17@RunWith(MockitoJUnitRunner.class)18public class CityServiceTest {19 @Mock20 private CityDao cityDao;21 private CityService cityService;22 private CityEntity moscow;23 private CityEntity tver;24 private CityEntity pskov;25 @Before26 public void setup() {27 cityService = new CityServiceImpl(cityDao);28 prefillTestData();29 defineMocks();30 }31 @Test32 public void addCity() throws DuplicateCityException {33 CityRecord newCity = new CityRecord();34 newCity.setName("СанкÑ-ÐеÑеÑбÑÑг");35 cityService.add(newCity);36 Mockito.verify(cityDao, VerificationModeFactory.times(1)).add(Mockito.any(CityEntity.class));37 }38 @Test(expected = DuplicateCityException.class)39 public void addDuplicateCity() throws DuplicateCityException {40 CityRecord newCity = new CityRecord();41 newCity.setName("ÐоÑква");42 cityService.add(newCity);43 Mockito.verify(cityDao, VerificationModeFactory.times(1)).add(Mockito.any(CityEntity.class));44 }45 @Test46 public void findById() {47 CityEntity city = cityService.findById(1L);48 Assert.assertEquals(moscow, city);49 }50 @Test (expected = EntityNotFoundException.class)51 public void findNonexistentCityById() {52 cityService.findById(100L);53 }54 @Test55 public void removeCity() {56 cityService.remove(1L);57 Mockito.verify(cityDao, VerificationModeFactory.times(1)).remove(moscow);58 }59 @Test (expected = EntityNotFoundException.class)60 public void removeNonexistentCity() {61 cityService.remove(100L);62 }63 @Test64 public void listAll() {65 cityService.listAll();66 Mockito.verify(cityDao, VerificationModeFactory.times(1)).listAll();67 }68 private void prefillTestData () {69 moscow = new CityEntity();70 moscow.setId(1);71 moscow.setName("ÐоÑква");72 tver = new CityEntity();73 tver.setId(2);74 tver.setName("ТвеÑÑ");75 pskov = new CityEntity();76 pskov.setId(6);77 pskov.setName("ÐÑков");78 }79 private void defineMocks() {80 Mockito.when(cityDao.findById(1L)).thenReturn(moscow);...
Source:Timeout.java
...3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.verification;67import org.mockito.internal.verification.VerificationModeFactory;8import org.mockito.internal.verification.VerificationWithTimeoutImpl;9import org.mockito.internal.verification.api.VerificationData;1011/**12 * See the javadoc for {@link VerificationWithTimeout}13 */14public class Timeout implements VerificationWithTimeout {1516 VerificationWithTimeoutImpl impl;1718 /**19 * See the javadoc for {@link VerificationWithTimeout}20 */21 public Timeout(int millis, VerificationMode delegate) {22 this(10, millis, delegate);23 }2425 Timeout(int treshhold, int millis, VerificationMode delegate) {26 this.impl = new VerificationWithTimeoutImpl(treshhold, millis, delegate);27 }2829 public void verify(VerificationData data) {30 impl.verify(data);31 }3233 public VerificationMode atLeast(int minNumberOfInvocations) {34 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.atLeast(minNumberOfInvocations));35 }3637 public VerificationMode atLeastOnce() {38 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.atLeastOnce());39 }4041 public VerificationMode atMost(int maxNumberOfInvocations) {42 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.atMost(maxNumberOfInvocations));43 }4445 public VerificationMode never() {46 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.times(0));47 }4849 public VerificationMode only() {50 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.only());51 }5253 public VerificationMode times(int wantedNumberOfInvocations) {54 return new Timeout(impl.getTreshhold(), impl.getTimeout(), VerificationModeFactory.times(wantedNumberOfInvocations));55 }
...
Source:VerificationWrapper.java
...18 protected abstract VerificationMode copySelfWithNewVerificationMode(19 VerificationMode verificationMode);20 public VerificationMode times(int wantedNumberOfInvocations) {21 return copySelfWithNewVerificationMode(22 VerificationModeFactory.times(wantedNumberOfInvocations));23 }24 public VerificationMode never() {25 return copySelfWithNewVerificationMode(VerificationModeFactory.atMost(0));26 }27 public VerificationMode atLeastOnce() {28 return copySelfWithNewVerificationMode(VerificationModeFactory.atLeastOnce());29 }30 public VerificationMode atLeast(int minNumberOfInvocations) {31 return copySelfWithNewVerificationMode(32 VerificationModeFactory.atLeast(minNumberOfInvocations));33 }34 public VerificationMode atMostOnce() {35 return copySelfWithNewVerificationMode(VerificationModeFactory.atMostOnce());36 }37 public VerificationMode atMost(int maxNumberOfInvocations) {38 return copySelfWithNewVerificationMode(39 VerificationModeFactory.atMost(maxNumberOfInvocations));40 }41 public VerificationMode only() {42 return copySelfWithNewVerificationMode(VerificationModeFactory.only());43 }44}...
VerificationModeFactory
Using AI Code Generation
1package org.kodejava.example.mockito;2import org.junit.Test;3import org.mockito.Mockito;4import java.util.List;5import static org.mockito.Mockito.*;6public class VerificationModeFactoryTest {7 public void testVerificationModeFactory() {8 List list = mock(List.class);9 when(list.get(0)).thenReturn("First");10 when(list.get(1)).thenReturn("Second");11 System.out.println(list.get(0));12 System.out.println(list.get(1));13 verify(list, Mockito.atLeastOnce()).get(0);14 verify(list, Mockito.atLeast(1)).get(1);15 }16}
VerificationModeFactory
Using AI Code Generation
1package org.mockito.internal.verification;2import org.mockito.internal.verification.api.VerificationData;3import org.mockito.verification.VerificationMode;4public class VerificationModeFactory {5 public static VerificationMode times(int wantedNumberOfInvocations) {6 return new Times(wantedNumberOfInvocations);7 }8 public static VerificationMode atLeastOnce() {9 return new AtLeast(1);10 }11 public static VerificationMode atLeast(int minNumberOfInvocations) {12 return new AtLeast(minNumberOfInvocations);13 }14 public static VerificationMode atMost(int maxNumberOfInvocations) {15 return new AtMost(maxNumberOfInvocations);16 }17 public static VerificationMode never() {18 return new AtMost(0);19 }20 public static VerificationMode only() {21 return new Only();22 }23 public static VerificationMode noMoreInteractions() {24 return new NoMoreInteractions();25 }26 public static VerificationMode description(String description) {27 return new DescribedAs(description);28 }29 public static VerificationMode after(int wantedNumberOfInvocations) {30 return new After(wantedNumberOfInvocations);31 }32 public static VerificationMode after(long millis) {33 return new After(millis);34 }35 public static VerificationMode timeout(long millis) {36 return new Timeout(millis);37 }38 public static VerificationMode timeout(long millis, VerificationMode verificationMode) {39 return new Timeout(millis, verificationMode);40 }41 public static VerificationMode timeout(long millis, VerificationData data) {42 return new Timeout(millis, data);43 }44}45package org.mockito.internal.verification;46import org.mockito.internal.invocation.Invocation;47import org.mockito.internal.invocation.InvocationMatcher;48import org.mockito.internal.invocation.InvocationsFinder;49import org.mockito.internal.invocation.InvocationsFinderImpl;50import org.mockito.internal.invocation.MatchersBinder;51import org.mockito.internal.invocation.MatchersBinderImpl;52import org.mockito.internal.invocation.RealMethod;53import org.mockito.internal.invocation.RealMethodDispatcher;54import org.mockito.internal.invocation.RealMethodDispatcherImpl;55import org.mockito.internal.invocation.RealMethodInOrderImpl;56import org.mockito.internal.invocation.RealMethodInSequenceImpl;57import org.mockito.internal.invocation.RealMethodInSequenceOrAfterImpl;58import org.mockito.internal.invocation.RealMethodInSequenceOrAfterWithTimesImpl;59import
VerificationModeFactory
Using AI Code Generation
1package org.mockito.internal.verification;2import org.mockito.exceptions.base.MockitoException;3import org.mockito.internal.invocation.InvocationMatcher;4import org.mockito.internal.invocation.InvocationsFinder;5import org.mockito.internal.progress.VerificationMode;6import org.mockito.internal.progress.VerificationModeImpl;7import org.mockito.internal.stubbing.answers.CallsRealMethods;8import org.mockito.invocation.Invocation;9import org.mockito.invocation.MatchableInvocation;10import org.mockito.verification.VerificationData;11import java.util.List;12public class VerificationModeFactory {13 public static VerificationMode times(int wantedNumberOfInvocations) {14 return new VerificationModeImpl(wantedNumberOfInvocations, false);15 }16 public static VerificationMode atLeastOnce() {17 return new VerificationModeImpl(1, true);18 }19 public static VerificationMode atLeast(int wantedNumberOfInvocations) {20 if (wantedNumberOfInvocations < 1) {21 throw new MockitoException("Wanted at least 1 but was " + wantedNumberOfInvocations);22 }23 return new VerificationModeImpl(wantedNumberOfInvocations, true);24 }25 public static VerificationMode atMost(int wantedNumberOfInvocations) {26 if (wantedNumberOfInvocations < 0) {27 throw new MockitoException("Wanted at most 0 but was " + wantedNumberOfInvocations);28 }29 return new VerificationModeImpl(wantedNumberOfInvocations, false);30 }31 public static VerificationMode noMoreInteractions() {32 return new NoMoreInteractionsVerifier();33 }34 public static VerificationMode only() {35 return new OnlyVerified();36 }37 public static VerificationMode description(String description) {38 return new DescribedVerificationMode(description);39 }40 public static VerificationMode description(VerificationMode mode, String description) {41 return new DescribedVerificationMode(mode, description);42 }43 public static VerificationMode description(VerificationMode mode, String description, Object... args) {44 return new DescribedVerificationMode(mode, description, args);45 }46 public static VerificationMode description(VerificationMode mode, String description, Object arg) {47 return new DescribedVerificationMode(mode, description, arg);48 }49 public static VerificationMode description(VerificationMode mode, String description, Object arg1, Object arg2) {50 return new DescribedVerificationMode(mode, description, arg1, arg2);51 }52 public static VerificationMode description(VerificationMode mode, String description, Object arg1
VerificationModeFactory
Using AI Code Generation
1package org.mockito.internal.verification;2import org.mockito.Mockito;3import org.mockito.exceptions.verification.NoInteractionsWanted;4import org.mockito.exceptions.verification.TooManyActualInvocations;5import org.mockito.exceptions.verification.WantedButNotInvoked;6import org.mockito.internal.verification.api.VerificationData;7import org.mockito.verification.VerificationMode;8import org.mockito.verification.VerificationWithTimeout;9import java.util.concurrent.TimeUnit;10public class VerificationModeFactory {11 public static VerificationMode noMoreInteractions() {12 return new NoMoreInteractions();13 }14 public static VerificationMode noMoreInteractions(VerificationData data) {15 return new NoMoreInteractions(data);16 }17 public static VerificationMode atLeast(int wantedNumberOfInvocations) {18 return new AtLeast(wantedNumberOfInvocations);19 }20 public static VerificationMode atLeastOnce() {21 return new AtLeastOnce();22 }23 public static VerificationMode only() {24 return new Only();25 }26 public static VerificationMode times(int wantedNumberOfInvocations) {27 return new Times(wantedNumberOfInvocations);28 }29 public static VerificationMode atMost(int wantedNumberOfInvocations) {30 return new AtMost(wantedNumberOfInvocations);31 }32 public static VerificationMode atMostOnce() {33 return new AtMostOnce();34 }35 public static VerificationMode description(String description) {36 return new DescribedAs(description);37 }38 public static VerificationMode description(String description, VerificationMode mode) {39 return new DescribedAs(description, mode);40 }41 public static VerificationWithTimeout timeout(long millis) {42 return new Timeout(millis, TimeUnit.MILLISECONDS);43 }44 public static VerificationWithTimeout timeout(long time, TimeUnit unit) {45 return new Timeout(time, unit);46 }47 public static VerificationMode after(long millis) {48 return new After(millis, TimeUnit.MILLISECONDS);49 }50 public static VerificationMode after(long time, TimeUnit unit) {51 return new After(time, unit);52 }53 public static VerificationMode never() {54 return new Never();55 }56 public static VerificationMode calls(int wantedNumberOfInvocations) {57 return new Calls(wantedNumberOfInvocations);58 }59 public static VerificationMode call(int wantedNumberOfInvocations) {60 return new Calls(wantedNumberOfInvocations);61 }62 public static VerificationMode callRealMethod() {63 return new CallRealMethod();64 }
VerificationModeFactory
Using AI Code Generation
1package org.letcode;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import static org.mockito.Mockito.when;5import static org.mockito.internal.verification.VerificationModeFactory.times;6import java.util.List;7import org.junit.Test;8public class MockitoTest {9public void test() {10List mockList = mock(List.class);11mockList.add("one");12mockList.clear();13verify(mockList).add("one");14verify(mockList).clear();15}16public void test2() {17List mockList = mock(List.class);18mockList.add("one");19mockList.clear();20verify(mockList, times(1)).add("one");21verify(mockList, times(1)).clear();22}23}24MockitoTest > test() PASSED25MockitoTest > test2() PASSED26BUILD SUCCESSFUL (total time: 0 seconds)
VerificationModeFactory
Using AI Code Generation
1package org.mockito.internal.verification;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.runners.MockitoJUnitRunner;6import java.util.LinkedList;7import java.util.List;8import static org.mockito.Mockito.*;9@RunWith(MockitoJUnitRunner.class)10public class VerificationModeFactoryTest {11 private List<String> list;12 public void testVerificationModeFactory() {13 List mockedList = mock(List.class);14 mockedList.add("one");15 mockedList.clear();16 verify(mockedList).add("one");17 verify(mockedList).clear();18 verify(mockedList, times(1)).add("one");19 verify(mockedList, times(1)).clear();20 verify(mockedList, atLeastOnce()).add("one");21 verify(mockedList, atLeastOnce()).clear();22 verify(mockedList, atLeast(1)).add("one");23 verify(mockedList, atLeast(1)).clear();24 verify(mockedList, atMostOnce()).add("one");25 verify(mockedList, atMostOnce()).clear();26 verify(mockedList, atMost(1)).add("one");27 verify(mockedList, atMost(1)).clear();28 verify(mockedList, atMost(2)).add("one");29 verify(mockedList, atMost(2)).clear();30 verify(mockedList, never()).add("two");31 verify(mockedList, never()).clear();32 verify(mockedList, times(0)).add("two");33 verify(mockedList, times(0)).clear();34 verify(mockedList, atLeast(2)).add("one");35 verify(mockedList, atLeast(2)).clear();36 verify(mockedList, atLeast(0)).add("one");37 verify(mockedList, atLeast(0)).clear();38 verify(mockedList, atMost(0)).add("one");39 verify(mockedList, atMost(0)).clear();40 verify(mockedList, atMost(3)).add("one");41 verify(mockedList, atMost(3)).clear();42 verify(mockedList, VerificationModeFactory.times(1)).add("one");43 verify(mockedList, VerificationModeFactory.times(1)).clear();44 verify(mockedList, VerificationModeFactory.atLeastOnce()).add("one");45 verify(mockedList, VerificationModeFactory.atLeastOnce()).clear();46 verify(mock
VerificationModeFactory
Using AI Code Generation
1package com.automationrhapsody.mockito;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.List;5import org.junit.Test;6public class MockitoVerifyTest {7 public void testVerify() {8 List<String> mockedList = mock(List.class);9 mockedList.add("one");10 mockedList.add("two");11 mockedList.add("three");12 verify(mockedList, VerificationModeFactory.times(3)).add(Mockito.anyString());13 }14}15package com.automationrhapsody.mockito;16import static org.mockito.Mockito.mock;17import static org.mockito.Mockito.verify;18import java.util.List;19import org.junit.Test;20public class MockitoVerifyTest {21 public void testVerify() {22 List<String> mockedList = mock(List.class);23 mockedList.add("one");24 mockedList.add("two");25 mockedList.add("three");26 verify(mockedList, VerificationModeFactory.times(3)).add(Mockito.anyString());27 }28}29package com.automationrhapsody.mockito;30import static org.mockito.Mockito.mock;31import static org.mockito.Mockito.verify;32import java.util.List;33import org.junit.Test;34public class MockitoVerifyTest {35 public void testVerify() {36 List<String> mockedList = mock(List.class);37 mockedList.add("one");38 mockedList.add("two");39 mockedList.add("three");40 verify(mockedList, VerificationModeFactory.times(3)).add(Mockito.anyString());41 }42}43package com.automationrhapsody.mockito;44import static org.mockito.Mockito.mock;45import static org.mockito.Mockito.verify;46import java.util.List;47import org.junit.Test;48public class MockitoVerifyTest {49 public void testVerify() {50 List<String> mockedList = mock(List.class);51 mockedList.add("one");
VerificationModeFactory
Using AI Code Generation
1package mockito;2import static org.mockito.Mockito.*;3import org.mockito.internal.verification.VerificationModeFactory;4import org.junit.Test;5public class MockitoTest {6 public void test() {7 Employee e = mock(Employee.class);8 verify(e, VerificationModeFactory.times(0)).getEmployeeName();9 }10}11package mockito;12import static org.mockito.Mockito.*;13import org.mockito.internal.verification.VerificationModeFactory;14import org.junit.Test;15public class MockitoTest {16 public void test() {17 Employee e = mock(Employee.class);18 verify(e, VerificationModeFactory.times(0)).getEmployeeName();19 }20}21Related Posts: Mockito – verify() method22Mockito – verifyZeroInteractions() method23Mockito – times() method24Mockito – never() method25Mockito – atLeast() method26Mockito – atLeastOnce() method27Mockito – atMost() method28Mockito – only() method29Mockito – timeout() method30Mockito – after() method31Mockito – VerificationModeFactory.times() method32Mockito – VerificationModeFactory.atLeast() method33Mockito – VerificationModeFactory.atMost() method34Mockito – VerificationModeFactory.atLeastOnce() method35Mockito – VerificationModeFactory.never() method36Mockito – VerificationModeFactory.only() method37Mockito – VerificationModeFactory.timeout() method
VerificationModeFactory
Using AI Code Generation
1public class Main {2 public static void main(String[] args) {3 List mockedList = mock(List.class);4 mockedList.add("one");5 mockedList.add("two");6 verify(mockedList, atLeastOnce()).add("one");7 }8}9public class Main {10 public static void main(String[] args) {11 List mockedList = mock(List.class);12 mockedList.add("one");13 mockedList.add("two");14 verify(mockedList, atLeastOnce()).add("two");15 }16}17public class Main {18 public static void main(String[] args) {19 List mockedList = mock(List.class);20 mockedList.add("one");21 mockedList.add("two");22 verify(mockedList, atLeastOnce()).add("three");23 }24}25public class Main {26 public static void main(String[] args) {27 List mockedList = mock(List.class);28 mockedList.add("one");29 mockedList.add("two");30 verify(mockedList, atLeastOnce()).add("two");31 }32}33public class Main {34 public static void main(String[] args) {
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!!