Best Mockito code snippet using org.mockito.ArgumentMatchers.startsWith
Source:SystemAppUninstallerTest.java
...59 @Test60 public void uninstallPackage_packageIsNotInstalled_doesNotRemove() throws Exception {61 ITestDevice device = createGoodDeviceWithAppNotInstalled();62 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);63 Mockito.verify(device, Mockito.times(0)).executeShellV2Command(Mockito.startsWith("rm"));64 }65 @Test66 public void uninstallPackage_differentPackageWithSameNamePrefixInstalled_doesNotRemove()67 throws Exception {68 ITestDevice device = createGoodDeviceWithSystemAppInstalled();69 // Mock the device as if the test package does not exist on device70 CommandResult commandResult = createSuccessfulCommandResult();71 commandResult.setStdout(String.format("package:%s_some_more_chars", TEST_PACKAGE_NAME));72 Mockito.when(73 device.executeShellV2Command(74 ArgumentMatchers.startsWith(75 CHECK_PACKAGE_INSTALLED_COMMAND_PREFIX)))76 .thenReturn(commandResult);77 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);78 Mockito.verify(device, Mockito.times(0)).executeShellV2Command(Mockito.startsWith("rm"));79 }80 @Test81 public void uninstallPackage_checkPackageInstalledCommandFailed_throws() throws Exception {82 ITestDevice device = createGoodDeviceWithSystemAppInstalled();83 Mockito.when(84 device.executeShellV2Command(85 ArgumentMatchers.startsWith(86 CHECK_PACKAGE_INSTALLED_COMMAND_PREFIX)))87 .thenReturn(createFailedCommandResult());88 assertThrows(89 TargetSetupError.class,90 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));91 }92 @Test93 public void uninstallPackage_getInstallDirectoryCommandFailed_throws() throws Exception {94 ITestDevice device = createGoodDeviceWithSystemAppInstalled();95 Mockito.when(96 device.executeShellV2Command(97 ArgumentMatchers.startsWith(98 GET_PACKAGE_INSTALL_PATH_COMMAND_PREFIX)))99 .thenReturn(createFailedCommandResult());100 assertThrows(101 TargetSetupError.class,102 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));103 }104 @Test105 public void uninstallPackage_packageIsNotSystemApp_doesNotRemove() throws Exception {106 ITestDevice device = createGoodDeviceWithUserAppInstalled();107 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);108 Mockito.verify(device, Mockito.times(0)).executeShellV2Command(Mockito.startsWith("rm"));109 }110 @Test111 public void uninstallPackage_adbAlreadyRooted_doesNotRootAgain() throws Exception {112 ITestDevice device = createGoodDeviceWithSystemAppInstalled();113 Mockito.when(device.isAdbRoot()).thenReturn(true);114 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);115 Mockito.verify(device, Mockito.times(0)).enableAdbRoot();116 }117 @Test118 public void uninstallPackage_adbNotAlreadyRooted_rootAdbAndThenUnroot() throws Exception {119 ITestDevice device = createGoodDeviceWithSystemAppInstalled();120 Mockito.when(device.isAdbRoot()).thenReturn(false);121 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);122 Mockito.verify(device, Mockito.times(1)).enableAdbRoot();123 Mockito.verify(device, Mockito.times(1)).disableAdbRoot();124 }125 @Test126 public void uninstallPackage_adbRootCommandFailed_throws() throws Exception {127 ITestDevice device = createGoodDeviceWithSystemAppInstalled();128 Mockito.when(device.enableAdbRoot()).thenThrow(new DeviceNotAvailableException());129 assertThrows(130 DeviceNotAvailableException.class,131 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));132 }133 @Test134 public void uninstallPackage_adbRootFailed_throws() throws Exception {135 ITestDevice device = createGoodDeviceWithSystemAppInstalled();136 Mockito.when(device.enableAdbRoot()).thenReturn(false);137 assertThrows(138 TargetSetupError.class,139 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));140 }141 @Test142 public void uninstallPackage_adbDisableRootCommandFailed_throws() throws Exception {143 ITestDevice device = createGoodDeviceWithSystemAppInstalled();144 Mockito.when(device.disableAdbRoot()).thenThrow(new DeviceNotAvailableException());145 assertThrows(146 DeviceNotAvailableException.class,147 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));148 }149 @Test150 public void uninstallPackage_adbDisableRootFailed_throws() throws Exception {151 ITestDevice device = createGoodDeviceWithSystemAppInstalled();152 Mockito.when(device.disableAdbRoot()).thenReturn(false);153 assertThrows(154 TargetSetupError.class,155 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));156 }157 @Test158 public void uninstallPackage_adbRemountFailed_throws() throws Exception {159 ITestDevice device = createGoodDeviceWithSystemAppInstalled();160 Mockito.doThrow(new DeviceNotAvailableException()).when(device).remountSystemWritable();161 assertThrows(162 DeviceNotAvailableException.class,163 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));164 }165 @Test166 public void uninstallPackage_adbRemounted_mountReadOnlyAfterwards() throws Exception {167 ITestDevice device = createGoodDeviceWithSystemAppInstalled();168 Mockito.doNothing().when(device).remountSystemWritable();169 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);170 Mockito.verify(device, Mockito.times(1)).remountSystemWritable();171 Mockito.verify(device, Mockito.times(1))172 .executeShellV2Command(Mockito.startsWith(MOUNT_COMMAND_PREFIX));173 }174 @Test175 public void uninstallPackage_mountReadOnlyFailed_throws() throws Exception {176 ITestDevice device = createGoodDeviceWithSystemAppInstalled();177 Mockito.when(178 device.executeShellV2Command(179 ArgumentMatchers.startsWith(MOUNT_COMMAND_PREFIX)))180 .thenReturn(createFailedCommandResult());181 assertThrows(182 TargetSetupError.class,183 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));184 }185 @Test186 public void uninstallPackage_removePackageInstallDirectoryFailed_throws() throws Exception {187 ITestDevice device = createGoodDeviceWithSystemAppInstalled();188 Mockito.when(189 device.executeShellV2Command(190 ArgumentMatchers.startsWith(REMOVE_SYSTEM_APP_COMMAND_PREFIX)))191 .thenReturn(createFailedCommandResult());192 assertThrows(193 TargetSetupError.class,194 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));195 }196 @Test197 public void uninstallPackage_removePackageDataDirectoryFailed_doesNotThrow() throws Exception {198 ITestDevice device = createGoodDeviceWithSystemAppInstalled();199 Mockito.when(200 device.executeShellV2Command(201 ArgumentMatchers.startsWith(REMOVE_APP_DATA_COMMAND_PREFIX)))202 .thenReturn(createFailedCommandResult());203 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);204 }205 @Test206 public void uninstallPackage_packageIsSystemApp_appRemoved() throws Exception {207 ITestDevice device = createGoodDeviceWithSystemAppInstalled();208 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);209 Mockito.verify(device, Mockito.times(1))210 .executeShellV2Command(Mockito.startsWith(REMOVE_SYSTEM_APP_COMMAND_PREFIX));211 Mockito.verify(device, Mockito.times(1))212 .executeShellV2Command(Mockito.startsWith(REMOVE_APP_DATA_COMMAND_PREFIX));213 }214 @Test215 public void uninstallPackage_noUpdatePackagePresent_appRemoved() throws Exception {216 int numberOfUpdates = 0;217 ITestDevice device = createGoodDeviceWithSystemAppInstalled(numberOfUpdates);218 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);219 Mockito.verify(device, Mockito.times(numberOfUpdates + 1))220 .uninstallPackage(TEST_PACKAGE_NAME);221 Mockito.verify(device, Mockito.times(1))222 .executeShellV2Command(Mockito.startsWith(REMOVE_SYSTEM_APP_COMMAND_PREFIX));223 }224 @Test225 public void uninstallPackage_someUpdatePackagesPresent_appRemoved() throws Exception {226 int numberOfUpdates = 2;227 ITestDevice device = createGoodDeviceWithSystemAppInstalled(numberOfUpdates);228 SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device);229 Mockito.verify(device, Mockito.times(numberOfUpdates + 1))230 .uninstallPackage(TEST_PACKAGE_NAME);231 Mockito.verify(device, Mockito.times(1))232 .executeShellV2Command(Mockito.startsWith(REMOVE_SYSTEM_APP_COMMAND_PREFIX));233 }234 @Test235 public void uninstallPackage_tooManyUpdatePackagesPresent_throwsException() throws Exception {236 ITestDevice device =237 createGoodDeviceWithSystemAppInstalled(238 SystemPackageUninstaller.MAX_NUMBER_OF_UPDATES + 1);239 assertThrows(240 TargetSetupError.class,241 () -> SystemPackageUninstaller.uninstallPackage(TEST_PACKAGE_NAME, device));242 }243 private ITestDevice createGoodDeviceWithUserAppInstalled() throws Exception {244 ITestDevice device = createGoodDeviceWithSystemAppInstalled();245 CommandResult commandResult = createSuccessfulCommandResult();246 commandResult.setStdout(247 String.format("package:/data/app/%s/%s.apk", TEST_PACKAGE_NAME, TEST_PACKAGE_NAME));248 Mockito.when(249 device.executeShellV2Command(250 ArgumentMatchers.startsWith(251 GET_PACKAGE_INSTALL_PATH_COMMAND_PREFIX)))252 .thenReturn(commandResult);253 return device;254 }255 private ITestDevice createGoodDeviceWithAppNotInstalled() throws Exception {256 ITestDevice device = createGoodDeviceWithSystemAppInstalled();257 CommandResult commandResult = createSuccessfulCommandResult();258 commandResult.setStdout("");259 Mockito.when(260 device.executeShellV2Command(261 ArgumentMatchers.startsWith(262 CHECK_PACKAGE_INSTALLED_COMMAND_PREFIX)))263 .thenReturn(commandResult);264 return device;265 }266 private ITestDevice createGoodDeviceWithSystemAppInstalled() throws Exception {267 return createGoodDeviceWithSystemAppInstalled(1);268 }269 private ITestDevice createGoodDeviceWithSystemAppInstalled(int numberOfUpdatesInstalled)270 throws Exception {271 ITestDevice device = Mockito.mock(ITestDevice.class);272 CommandResult commandResult;273 // Is framework running274 Mockito.when(275 device.executeShellV2Command(276 ArgumentMatchers.eq(SystemPackageUninstaller.PM_CHECK_COMMAND)))277 .thenReturn(createSuccessfulCommandResult());278 // Uninstall updates279 String uninstallFailureMessage = "Failure [DELETE_FAILED_INTERNAL_ERROR]";280 if (numberOfUpdatesInstalled == 0) {281 Mockito.when(device.uninstallPackage(TEST_PACKAGE_NAME))282 .thenReturn(uninstallFailureMessage);283 } else {284 String[] uninstallResults = new String[numberOfUpdatesInstalled];285 uninstallResults[numberOfUpdatesInstalled - 1] = uninstallFailureMessage;286 Mockito.when(device.uninstallPackage(TEST_PACKAGE_NAME))287 .thenReturn(null, uninstallResults);288 }289 // List package290 commandResult = createSuccessfulCommandResult();291 commandResult.setStdout("package:" + TEST_PACKAGE_NAME);292 Mockito.when(293 device.executeShellV2Command(294 ArgumentMatchers.startsWith(295 CHECK_PACKAGE_INSTALLED_COMMAND_PREFIX)))296 .thenReturn(commandResult);297 // Get package path298 commandResult = createSuccessfulCommandResult();299 commandResult.setStdout(300 String.format(301 "package:%s/%s/%s.apk",302 SYSTEM_APP_INSTALL_DIRECTORY, TEST_PACKAGE_NAME, TEST_PACKAGE_NAME));303 Mockito.when(304 device.executeShellV2Command(305 ArgumentMatchers.startsWith(306 GET_PACKAGE_INSTALL_PATH_COMMAND_PREFIX)))307 .thenReturn(commandResult);308 // Adb root309 Mockito.when(device.isAdbRoot()).thenReturn(false);310 Mockito.when(device.enableAdbRoot()).thenReturn(true);311 // Adb remount312 Mockito.doNothing().when(device).remountSystemWritable();313 // Remove package install directory314 Mockito.when(315 device.executeShellV2Command(316 ArgumentMatchers.startsWith(REMOVE_SYSTEM_APP_COMMAND_PREFIX)))317 .thenReturn(createSuccessfulCommandResult());318 // Remove package data directory319 Mockito.when(320 device.executeShellV2Command(321 ArgumentMatchers.startsWith(REMOVE_APP_DATA_COMMAND_PREFIX)))322 .thenReturn(createSuccessfulCommandResult());323 // Restart framework324 Mockito.when(device.executeShellV2Command(ArgumentMatchers.eq("start")))325 .thenReturn(createSuccessfulCommandResult());326 Mockito.when(device.executeShellV2Command(ArgumentMatchers.eq("stop")))327 .thenReturn(createSuccessfulCommandResult());328 // Disable adb root329 Mockito.when(device.disableAdbRoot()).thenReturn(true);330 // Remount read only331 Mockito.when(332 device.executeShellV2Command(333 ArgumentMatchers.startsWith(MOUNT_COMMAND_PREFIX)))334 .thenReturn(createSuccessfulCommandResult());335 return device;336 }337 private static CommandResult createSuccessfulCommandResult() {338 CommandResult commandResult = new CommandResult(CommandStatus.SUCCESS);339 commandResult.setExitCode(0);340 return commandResult;341 }342 private static CommandResult createFailedCommandResult() {343 CommandResult commandResult = new CommandResult(CommandStatus.FAILED);344 commandResult.setExitCode(1);345 return commandResult;346 }347}...
Source:MatchersMixin.java
...329 default short shortThat(ArgumentMatcher<Short> matcher) {330 return ArgumentMatchers.shortThat(matcher);331 }332 /**333 * Delegate call to public static java.lang.String org.mockito.ArgumentMatchers.startsWith(java.lang.String)334 * {@link org.mockito.ArgumentMatchers#startsWith(java.lang.String)}335 */336 default String startsWith(String prefix) {337 return ArgumentMatchers.startsWith(prefix);338 }339}...
Source:VMCompositionExportSessionImplInstrumentationTest.java
...21import static org.hamcrest.Matchers.not;22import static org.junit.Assert.assertThat;23import static org.mockito.ArgumentMatchers.anyLong;24import static org.mockito.ArgumentMatchers.anyString;25import static org.mockito.ArgumentMatchers.startsWith;26import static org.mockito.Mockito.never;27import static org.mockito.Mockito.verify;28/**29 * Created by jliarte on 22/09/17.30 */31public class VMCompositionExportSessionImplInstrumentationTest extends AssetManagerAndroidTest {32 private String testPath;33 @Mock private VMCompositionExportSession.ExportListener mockedExportListener;34 @Mock private TranscoderHelper mockedTranscoderHelper;35 @Before36 public void setUp() {37 MockitoAnnotations.initMocks(this);38 testPath = getInstrumentation().getTargetContext().getExternalCacheDir()39 .getAbsolutePath();40 }41 @Test42 public void testExportDoesntMixAudioWithJustOneVideoAndDefaultVolume()43 throws IllegalItemOnTrack, IOException {44 String originalVideoPath = getAssetPath("vid_.mp4");45 Video video = new Video(originalVideoPath, Video.DEFAULT_VOLUME);46 Profile profile = new Profile(VideoResolution.Resolution.HD720, VideoQuality.Quality.GOOD,47 VideoFrameRate.FrameRate.FPS30);48 VMComposition composition = new VMComposition(null, profile);49 composition.getMediaTrack().insertItem(video);50// int originalVideoDuration = Integer.parseInt(getVideoDuration(originalVideoPath));51 String tempFilesDirectory = testPath + "/tmp/";52 VMCompositionExportSessionImpl exportSession = new VMCompositionExportSessionImpl(composition,53 testPath, tempFilesDirectory, tempFilesDirectory, mockedExportListener);54 exportSession.transcoderHelper = mockedTranscoderHelper;55 exportSession.export();56 verify(mockedTranscoderHelper, never()).generateTempFileMixAudio(57 ArgumentMatchers.<Media>anyList(), anyString(), anyString(), anyLong());58 ArgumentCaptor<Object> videoCaptor = ArgumentCaptor.forClass(Video.class);59 verify(mockedExportListener).onExportSuccess((Video) videoCaptor.capture());60 Video exportedVideo = (Video) videoCaptor.getValue();61 assertThat(exportedVideo.getMediaPath(), not(startsWith(tempFilesDirectory)));62 assertThat(exportedVideo.getMediaPath(), not(containsString("V_Appended.mp4")));63 }64 @Test65 public void testExportMixAudioWithJustOneVideoAndNotDefaultVolume()66 throws IllegalItemOnTrack, IOException {67 String originalVideoPath = getAssetPath("vid_.mp4");68 Video video = new Video(originalVideoPath, 0.5f);69 Profile profile = new Profile(VideoResolution.Resolution.HD720, VideoQuality.Quality.GOOD,70 VideoFrameRate.FrameRate.FPS30);71 VMComposition composition = new VMComposition(null, profile);72 composition.getMediaTrack().insertItem(video);73// int originalVideoDuration = Integer.parseInt(getVideoDuration(originalVideoPath));74 String tempFilesDirectory = testPath + "/tmp/";75 VMCompositionExportSessionImpl exportSession = new VMCompositionExportSessionImpl(composition,76 testPath, tempFilesDirectory, tempFilesDirectory, mockedExportListener);77 exportSession.transcoderHelper = mockedTranscoderHelper;78 exportSession.export();79 verify(mockedTranscoderHelper).generateTempFileMixAudio(80 ArgumentMatchers.<Media>anyList(), anyString(), anyString(), anyLong());81 ArgumentCaptor<Object> videoCaptor = ArgumentCaptor.forClass(Video.class);82 verify(mockedExportListener).onExportSuccess((Video) videoCaptor.capture());83 Video exportedVideo = (Video) videoCaptor.getValue();84 assertThat(exportedVideo.getMediaPath(), not(startsWith(tempFilesDirectory)));85 assertThat(exportedVideo.getMediaPath(), not(containsString("V_Appended.mp4")));86 }87 private String getVideoDuration(String videoPath) {88 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();89 mediaMetadataRetriever.setDataSource(videoPath);90 return mediaMetadataRetriever91 .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);92 }93}...
Source:CssSupportImplTest.java
1package org.fluentlenium.core.css;2import static org.assertj.core.api.Assertions.assertThatThrownBy;3import static org.mockito.ArgumentMatchers.anyLong;4import static org.mockito.ArgumentMatchers.anyString;5import static org.mockito.ArgumentMatchers.startsWith;6import static org.mockito.Mockito.times;7import static org.mockito.Mockito.verify;8import static org.mockito.Mockito.verifyNoMoreInteractions;9import static org.mockito.Mockito.when;10import org.junit.Before;11import org.junit.Ignore;12import org.junit.Test;13import org.junit.runner.RunWith;14import org.mockito.Mock;15import org.mockito.junit.MockitoJUnitRunner;16import org.openqa.selenium.WebDriverException;17import org.fluentlenium.core.script.FluentJavascript;18import org.fluentlenium.core.script.JavascriptControl;19import org.fluentlenium.core.wait.AwaitControl;20import org.fluentlenium.core.wait.FluentWait;21/**22 * Unit test for {@link CssSupportImpl}.23 */24@RunWith(MockitoJUnitRunner.class)25public class CssSupportImplTest {26 private static final String CSS_TEXT = "some: css";27 @Mock28 private JavascriptControl javascriptControl;29 @Mock30 private AwaitControl awaitControl;31 @Mock32 private FluentJavascript fluentJavascript;33 @Mock34 private FluentWait fluentWait;35 @Mock36 private FluentWait fluentWaitExplicit;37 private CssSupportImpl cssSupport;38 @Before39 public void setup() {40 when(awaitControl.await()).thenReturn(fluentWait);41 when(fluentWait.explicitlyFor(anyLong())).thenReturn(fluentWaitExplicit);42 cssSupport = new CssSupportImpl(javascriptControl, awaitControl);43 }44 @Test45 public void shouldInjectCss() {46 when(javascriptControl.executeScript(anyString())).thenReturn(fluentJavascript);47 cssSupport.inject(CSS_TEXT);48 verify(javascriptControl, times(1)).executeScript(startsWith("cssText = \"some: css\";"));49 verifyNoMoreInteractions(javascriptControl);50 }51 @Test52 @Ignore("Find a way to mock IOUtils.toString() to throw exception")53 public void shouldThrowIOErrorDuringInjectingCss() {54 }55 @Test56 public void shouldInjectResource() {57 when(javascriptControl.executeScript(anyString())).thenReturn(fluentJavascript);58 cssSupport.injectResource("/org/fluentlenium/core/css/dummy_resource.js");59 verify(javascriptControl, times(1)).executeScript(startsWith("cssText = \"dummy: content\";"));60 verifyNoMoreInteractions(javascriptControl);61 }62 @Test63 @Ignore("Find a way to mock IOUtils.toString() to throw exception")64 public void shouldThrowIOErrorDuringInjectingResource() {65 }66 @Test67 public void shouldThrowNPEIfResourceIsNotFound() {68 String cssResourceName = "/an/invalid/path.js";69 assertThatThrownBy(() -> cssSupport.injectResource(cssResourceName)).isInstanceOf(NullPointerException.class);70 }71 @Test72 public void shouldThrowWebDriverExceptionBeforeReachingMaxRetryCount() {73 when(javascriptControl.executeScript(startsWith("cssText = \"some: css\";"))).thenThrow(WebDriverException.class)74 .thenReturn(fluentJavascript);75 cssSupport.inject(CSS_TEXT);76 verify(javascriptControl, times(2)).executeScript(startsWith("cssText = \"some: css\";"));77 verify(awaitControl, times(1)).await();78 verifyNoMoreInteractions(javascriptControl);79 verifyNoMoreInteractions(awaitControl);80 }81 @Test82 public void shouldThrowWebDriverExceptionAfterReachingMaxRetryCount() {83 when(javascriptControl.executeScript(startsWith("cssText = \"some: css\";"))).thenThrow(WebDriverException.class);84 assertThatThrownBy(() -> cssSupport.inject(CSS_TEXT)).isInstanceOf(WebDriverException.class);85 verify(javascriptControl, times(10)).executeScript(startsWith("cssText = \"some: css\";"));86 verify(awaitControl, times(9)).await();87 verifyNoMoreInteractions(javascriptControl);88 verifyNoMoreInteractions(awaitControl);89 }90}...
Source:FrankfurterRatesServiceConnectorTest.java
...21import static org.junit.jupiter.api.Assertions.assertThrows;22import static org.mockito.ArgumentMatchers.any;23import static org.mockito.ArgumentMatchers.anyString;24import static org.mockito.ArgumentMatchers.eq;25import static org.mockito.ArgumentMatchers.startsWith;26import static org.mockito.Mockito.verify;27import static org.mockito.Mockito.when;28@ExtendWith(MockitoExtension.class)29class FrankfurterRatesServiceConnectorTest {30 private static final String SERVICE_URL = "https://service";31 private static final String SERVICE_PATH = SERVICE_URL + "/latest";32 @Mock33 private Supplier<URI> serviceUri;34 @Mock35 private RestTemplate restTemplate;36 @InjectMocks37 private FrankfurterRatesServiceConnector sut;38 @ParameterizedTest39 @NullSource40 void getCurrencyExchangeRate_null_fromCurrency(Currency fromCurrency) {41 assertThrows(IllegalArgumentException.class,42 () -> sut.getCurrencyExchangeRate(fromCurrency, EUR));43 }44 @ParameterizedTest45 @NullSource46 void getCurrencyExchangeRate_null_toCurrency(Currency toCurrency) {47 assertThrows(IllegalArgumentException.class,48 () -> sut.getCurrencyExchangeRate(USD, toCurrency));49 }50 @Test51 void getCurrencyExchangeRate_ok() {52 when(serviceUri.get()).thenReturn(URI.create(SERVICE_URL));53 double expectedRate = Double.parseDouble("0.89952");54 when(restTemplate.getForObject(anyString(), any()))55 .thenReturn(new FrankfurterRates(USD, Maps.newHashMap(EUR, expectedRate)));56 BigDecimal actualRate = sut.getCurrencyExchangeRate(USD, EUR);57 assertEquals(expectedRate, actualRate.doubleValue());58 verify(restTemplate).getForObject(startsWith(SERVICE_PATH), eq(FrankfurterRates.class));59 verify(serviceUri).get();60 }61 @Test62 void getCurrencyExchangeRate_not_ok_RestClientException() {63 when(serviceUri.get()).thenReturn(URI.create(SERVICE_URL));64 when(restTemplate.getForObject(anyString(), any()))65 .thenThrow(new RestClientException("error"));66 assertThrows(ConnectorRuntimeException.class,67 () -> sut.getCurrencyExchangeRate(USD, EUR)68 );69 verify(restTemplate).getForObject(startsWith(SERVICE_PATH), eq(FrankfurterRates.class));70 verify(serviceUri).get();71 }72}...
Source:MockOpenAIREFundingDataProvider.java
...26 @Override27 public void init() throws IOException {28 OpenAIRERestConnector restConnector = Mockito.mock(OpenAIRERestConnector.class);29 when(restConnector.searchProjectByKeywords(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(),30 ArgumentMatchers.startsWith("mushroom"))).thenAnswer(new Answer<Response>() {31 public Response answer(InvocationOnMock invocation) {32 try {33 return OpenAIREHandler34 .unmarshal(this.getClass().getResourceAsStream("openaire-projects.xml"));35 } catch (JAXBException e) {36 e.printStackTrace();37 }38 return null;39 }40 });41 when(restConnector.searchProjectByKeywords(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(),42 AdditionalMatchers.not(ArgumentMatchers.startsWith("mushroom")))).thenAnswer(new Answer<Response>() {43 public Response answer(InvocationOnMock invocation) {44 try {45 return OpenAIREHandler46 .unmarshal(this.getClass().getResourceAsStream("openaire-no-projects.xml"));47 } catch (JAXBException e) {48 e.printStackTrace();49 }50 return null;51 }52 });53 when(restConnector.searchProjectByIDAndFunder(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(),54 ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenAnswer(new Answer<Response>() {55 public Response answer(InvocationOnMock invocation) {56 try {...
Source:MockOrcid.java
...23public class MockOrcid extends Orcidv3SolrAuthorityImpl {24 @Override25 public void init() {26 OrcidRestConnector orcidRestConnector = Mockito.mock(OrcidRestConnector.class);27 when(orcidRestConnector.get(ArgumentMatchers.startsWith("search?"), ArgumentMatchers.any()))28 .thenAnswer(new Answer<InputStream>() {29 @Override30 public InputStream answer(InvocationOnMock invocation) {31 return this.getClass().getResourceAsStream("orcid-search-noresults.xml");32 }33 });34 when(orcidRestConnector.get(ArgumentMatchers.startsWith("search?q=Bollini"), ArgumentMatchers.any()))35 .thenAnswer(new Answer<InputStream>() {36 @Override37 public InputStream answer(InvocationOnMock invocation) {38 return this.getClass().getResourceAsStream("orcid-search.xml");39 }40 });41 when(orcidRestConnector.get(ArgumentMatchers.endsWith("/person"), ArgumentMatchers.any()))42 .thenAnswer(new Answer<InputStream>() {43 @Override44 public InputStream answer(InvocationOnMock invocation) {45 return this.getClass().getResourceAsStream("orcid-person-record.xml");46 }47 });48 setOrcidRestConnector(orcidRestConnector);...
Source:StartpassDaoTest.java
1package de.kreth.clubhelperbackend.dao;2import static org.junit.Assert.assertEquals;3import static org.junit.Assert.assertNotNull;4import static org.mockito.ArgumentMatchers.anyString;5import static org.mockito.ArgumentMatchers.startsWith;6import static org.mockito.Mockito.mock;7import static org.mockito.Mockito.when;8import java.sql.PreparedStatement;9import java.sql.SQLException;10import java.util.ArrayList;11import java.util.List;12import org.junit.Before;13import org.junit.Test;14import org.mockito.ArgumentMatchers;15import org.springframework.jdbc.core.RowMapper;16import de.kreth.clubhelperbackend.dao.abstr.AbstractDao;17import de.kreth.clubhelperbackend.pojo.Startpass;18public class StartpassDaoTest extends AbstractDaoTest<Startpass> {19 PreparedStatement selectStartpaesse;20 21 @Before22 public void setupStatement() throws SQLException {23 selectStartpaesse = mock(PreparedStatement.class);24 when(connection.prepareStatement(startsWith("SELECT * FROM startpass_startrechte"))).thenReturn(selectStartpaesse);25 }26 @Test27 public void testGetForPersonId() {28 List<Startpass> list = new ArrayList<>();29 Startpass pass = new Startpass();30 pass.setId(1L);31 pass.setPersonId(1L);32 list.add(pass);33 when(jdbcTemplate.query(anyString(), ArgumentMatchers.<RowMapper<Startpass>>any())).thenReturn(list);34 StartpassDao startpassDao = (StartpassDao) dao;35 List<Startpass> startpaese = startpassDao.getForPersonId(1L);36 assertNotNull(startpaese);37 assertEquals(1, startpaese.size());38 }...
startsWith
Using AI Code Generation
1package com.automationrhapsody.junit;2import static org.mockito.ArgumentMatchers.startsWith;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.Mockito;6import org.mockito.junit.MockitoJUnitRunner;7@RunWith(MockitoJUnitRunner.class)8public class MockitoStartsWithTest {9 public void testStartsWith() {10 String str = "Automation Rhapsody";11 Mockito.verify(str, Mockito.times(1)).startsWith(startsWith("Automation"));12 }13}14package com.automationrhapsody.junit;15import static org.mockito.ArgumentMatchers.endsWith;16import org.junit.Test;17import org.junit.runner.RunWith;18import org.mockito.Mockito;19import org.mockito.junit.MockitoJUnitRunner;20@RunWith(MockitoJUnitRunner.class)21public class MockitoEndsWithTest {22 public void testEndsWith() {23 String str = "Automation Rhapsody";24 Mockito.verify(str, Mockito.times(1)).endsWith(endsWith("Rhapsody"));25 }26}27package com.automationrhapsody.junit;28import static org.mockito.ArgumentMatchers.contains;29import org.junit.Test;30import org.junit.runner.RunWith;31import org.mockito.Mockito;32import org.mockito.junit.MockitoJUnitRunner;33@RunWith(MockitoJUnitRunner.class)34public class MockitoContainsTest {35 public void testContains() {36 String str = "Automation Rhapsody";37 Mockito.verify(str, Mockito.times(1)).contains(contains("Rhapsody"));38 }39}40package com.automationrhapsody.junit;41import static org.mockito.ArgumentMatchers.matches;42import org.junit.Test;43import org.junit.runner.RunWith;44import org.mockito.Mockito;45import org.mockito.junit.MockitoJUnitRunner;46@RunWith(MockitoJUnitRunner.class)47public class MockitoMatchesTest {48 public void testMatches() {49 String str = "Automation Rhapsody";50 Mockito.verify(str, Mockito.times(1)).matches(matches("Automation.*"));51 }52}53package com.automationrhapsody.junit;54import static org.mockito.ArgumentMatchers.anyString;55import org.junit.Test;56import org.junit.runner.RunWith;57import org.mockito
startsWith
Using AI Code Generation
1package com.automationtesting;2import static org.mockito.ArgumentMatchers.startsWith;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import org.junit.Test;6public class StartsWithMethod {7 public void testStartsWith() {8 EmployeeService mock = mock(EmployeeService.class);9 when(mock.getEmployeeName(startsWith("A"))).thenReturn("John");10 String empName = mock.getEmployeeName("A");11 System.out.println("Employee Name: " + empName);12 }13}14endsWith() method of ArgumentMatchers class15endsWith(String suffix)16package com.automationtesting;17import static org.mockito.ArgumentMatchers.endsWith;18import static org.mockito.Mockito.mock;19import static org.mockito.Mockito.when;20import org.junit.Test;21public class EndsWithMethod {22 public void testEndsWith() {23 EmployeeService mock = mock(EmployeeService.class);24 when(mock.getEmployeeName(endsWith("A"))).thenReturn("John");25 String empName = mock.getEmployeeName("A");26 System.out.println("Employee Name: " + empName);27 }28}29any() method of ArgumentMatchers class30any(Class<T> clazz)
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3import java.util.List;4import java.util.ArrayList;5public class MockitoStartsWith {6 public static void main(String[] args) {7 List<String> mockedList = Mockito.mock(ArrayList.class);8 Mockito.when(mockedList.get(ArgumentMatchers.startsWith("test"))).thenReturn("mock");9 System.out.println(mockedList.get("test"));10 }11}12import org.mockito.ArgumentMatchers;13import org.mockito.Mockito;14import java.util.List;15import java.util.ArrayList;16public class MockitoEndsWith {17 public static void main(String[] args) {18 List<String> mockedList = Mockito.mock(ArrayList.class);19 Mockito.when(mockedList.get(ArgumentMatchers.endsWith("test"))).thenReturn("mock");20 System.out.println(mockedList.get("test"));21 }22}23import org.mockito.ArgumentMatchers;24import org.mockito.Mockito;25import java.util.List;26import java.util.ArrayList;27public class MockitoContains {28 public static void main(String[] args) {29 List<String> mockedList = Mockito.mock(ArrayList.class);30 Mockito.when(mockedList.get(ArgumentMatchers.contains("test"))).thenReturn("mock");31 System.out.println(mockedList.get("test"));32 }33}34import org.mockito.ArgumentMatchers;35import org.mockito.Mockito;36import java.util.List;37import java.util.ArrayList;38public class MockitoMatches {39 public static void main(String[] args) {40 List<String> mockedList = Mockito.mock(ArrayList.class);41 Mockito.when(mockedList.get(ArgumentMatchers.matches("test"))).thenReturn("mock");42 System.out.println(mockedList.get("test"));43 }44}45import org.mockito.ArgumentMatchers;46import org.mockito.Mockito;47import java.util.List;48import java.util.ArrayList;49public class MockitoAnyString {50 public static void main(String[] args) {51 List<String> mockedList = Mockito.mock(ArrayList.class);52 Mockito.when(mockedList.get(ArgumentMatchers.anyString())).thenReturn("mock");
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.mockito.Mockito;3public class 1 {4 public static void main(String[] args) {5 String str = "test";6 Mockito.mock(String.class);7 Mockito.when(str.startsWith(ArgumentMatchers.startsWith("t"))).thenReturn(true);8 System.out.println(str.startsWith("t"));9 }10}11Recommended Posts: Java | startsWith() method
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class 1 {3 public static void main(String[] args) {4 System.out.println(ArgumentMatchers.startsWith("abc"));5 }6}7Recommended Posts: Java | startsWith() method in String class8Java | endsWith() method in String class9Java | endsWith() method in File class10Java | endsWith() method in StringBuilder class11Java | endsWith() method in StringBuffer class12Java | endsWith() method in Path class13Java | endsWith() method in Pattern class14Java | endsWith() method in Matcher class15Java | endsWith() method in Name class16Java | endsWith() method in FileSystem class17Java | endsWith() method in FileSystemProvider class18Java | endsWith() method in FileStore class19Java | endsWith() method in FileSystems class20Java | endsWith() method in FileSystemLoopException class21Java | endsWith() method in FileSystemNotFoundException class22Java | endsWith() method in FileSystemAlreadyExistsException class23Java | endsWith() method in FileSystemException class24Java | endsWith() method in FileSystemProvider class25Java | endsWith() method in FileVisitOption class26Java | endsWith() method in FileVisitResult class27Java | endsWith() method in FileVisitor class28Java | endsWith() method in FileVisitOption class29Java | endsWith() method in FileVisitResult class30Java | endsWith() method in FileVisitor class31Java | endsWith() method in FileVisitOption class32Java | endsWith() method in FileVisitResult class33Java | endsWith() method in FileVisitor class34Java | endsWith() method in FileVisitOption class35Java | endsWith() method in FileVisitResult class36Java | endsWith() method in FileVisitor class37Java | endsWith() method in FileVisitOption class38Java | endsWith() method in FileVisitResult class39Java | endsWith() method in FileVisitor class40Java | endsWith() method in FileVisitOption class41Java | endsWith() method in FileVisitResult class42Java | endsWith() method in FileVisitor class
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class MockitoStartsWith {3 public static void main(String[] args) {4 String str = "abc";5 boolean result = ArgumentMatchers.startsWith(str).matches("ab");6 System.out.println(result);7 }8}
startsWith
Using AI Code Generation
1public class MockitoStartsWithExample {2 private List<String> mockedList = mock(List.class);3 public void testStartsWith() {4 mockedList.add("one");5 mockedList.add("two");6 mockedList.add("three");7 mockedList.add("four");8 mockedList.add("five");9 mockedList.add("six");10 mockedList.add("seven");11 mockedList.add("eight");12 mockedList.add("nine");13 mockedList.add("ten");14 when(mockedList.get(anyInt())).thenReturn("element");15 Assert.assertEquals("element", mockedList.get(0));16 Assert.assertEquals("element", mockedList.get(1));17 Assert.assertEquals("element", mockedList.get(2));18 Assert.assertEquals("element", mockedList.get(3));19 Assert.assertEquals("element", mockedList.get(4));20 Assert.assertEquals("element", mockedList.get(5));21 Assert.assertEquals("element", mockedList.get(6));22 Assert.assertEquals("element", mockedList.get(7));23 Assert.assertEquals("element", mockedList.get(8));24 Assert.assertEquals("element", mockedList.get(9));25 verify(mockedList, times(10)).get(anyInt());26 }27}
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2import org.junit.Test;3import static org.mockito.Mockito.*;4public class StartsWithTest {5 public void testStartsWith() {6 String str = "Hello World";7 String str1 = "Hello";8 String str2 = "Hi";9 assert ArgumentMatchers.startsWith(str1).matches(str);10 assert !ArgumentMatchers.startsWith(str2).matches(str);11 }12}
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class MockingExample {3 public static void main(String[] args) {4 String string = "This is a string";5 System.out.println(ArgumentMatchers.startsWith("This").matches(string));6 System.out.println(ArgumentMatchers.startsWith("is").matches(string));7 }8}
startsWith
Using AI Code Generation
1import org.mockito.ArgumentMatchers;2public class Test {3 public static void main(String[] args) {4 String str = "Welcome to Javatpoint portal";5 System.out.println("String starts with 'Welcome' : " + ArgumentMatchers.startsWith("Welcome").matches(str));6 System.out.println("String starts with 'welcome' : " + ArgumentMatchers.startsWith("welcome").matches(str));7 }8}
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!!