Foreach 循环: ArrayList, Primitive data, HashMap

Java foreach循环示例
本文通过三个示例展示了如何在Java中使用foreach循环遍历数组、集合和映射。包括基本的字符串数组遍历、整数列表的遍历以及哈希映射中键值对的遍历。
 
import java.util.ArrayList;
import java.util.HashMap; 
import java.util.Map;
 
 
 
 
 
public class ForEachLoop {
 
 
 
public static void main(String[] args) {
 
//Simple object or primitive type data loop
 
String[] names = { "Michal", "Mainel", "Merka" };
 
 
 
for (String name : names) {
 
System.out.println(name);
 
}
 
 
 
//Collection API loop
 
 
 
ArrayList<Integer> numbers = new ArrayList<Integer>();
 
//Autoboxing no need cast or creating object new Integer
 
numbers.add(123);
 
numbers.add(12);
 
numbers.add(12445);
 
 
 
for (Integer number : numbers) {
 
System.out.println(number.toString());
 
}
 
 
 
HashMap<String, Integer> nameAndAges = new HashMap<String, Integer>();
 
nameAndAges.put("Jurka", 18);
 
nameAndAges.put("Mina", 19);
 
nameAndAges.put("Michal", 29);
 
 
 
for (Map.Entry<String, Integer> entry : nameAndAges.entrySet()) {
 
System.out.println("Name : " + entry.getKey() + " age " + entry.getValue());
 
}
 
}
 
 
 
}
 
/* * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. */ package com.huawei.gts.testexecutor.util; import com.huawei.gts.testexecutor.dto.Action; import com.huawei.mateinfo.sdk.file.FileServiceManager; import com.huawei.mateinfo.sdk.file.service.FileService; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.openqa.selenium.*; import org.openqa.selenium.remote.RemoteWebDriver; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.HashMap; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.*; /** * 解析用例测试类 * * @since 2021-09-16 */ @PowerMockIgnore({"javax.management.*", "javax.crypto.*"}) // 忽略异常 @PrepareForTest({ FileUtils.class, FileServiceManager.class}) @RunWith(PowerMockRunner.class) public class SeleniumActionTest { private SeleniumAction seleniumAction = new SeleniumAction(); /** * 测试用例描述:测试获取webDriver * 预制条件:RemoteWebDriver * 操作步骤:执行get方法 * 预期结果:抛异常 */ @Test public void testGetWebDriver() throws Exception { try (MockedStatic<RemoteWebDriver> mockedWebDriver = mockStatic(RemoteWebDriver.class)) { mockedWebDriver.when(() -> new RemoteWebDriver(any(URL.class), any(Capabilities.class))).thenReturn(null); assertThrows(Error.class, () -> seleniumAction.getWebDriver()); } } /** * 测试用例描述:测试执行方法 * 预制条件:Action对象 * 操作步骤:调用execute方法 * 预期结果:抛指定异常 */ @Test public void testExecute() throws IOException { Action action = new Action(); action.setCommand("openUrl"); action.setValue("http://www.baidu.com"); action.setUrl("file://etc"); Action.Path path = new Action.Path(); path.setId("id"); path.setName("name"); path.setXpath(Collections.singletonList("/xpath")); path.setCss(Collections.singletonList("/css")); path.setControlType("adc"); action.setPath(path); WebDriver driver = PowerMockito.mock(RemoteWebDriver.class); WebElement webElement = PowerMockito.mock(WebElement.class); when(webElement.isDisplayed()).thenReturn(true); when(driver.findElement(By.id("id"))).thenThrow(new NoSuchElementException("")); when(driver.findElement(By.name("name"))).thenThrow(new NoSuchElementException("")); when(driver.findElement(By.xpath("/xpath"))).thenThrow(new NoSuchElementException("")); when(driver.findElement(By.cssSelector("/css"))).thenReturn(webElement); try (MockedStatic<FileUtils> mockedFileUtils = mockStatic(FileUtils.class); MockedStatic<FileServiceManager> mockedFileServiceManager = mockStatic(FileServiceManager.class)) { mockedFileUtils.when(() -> FileUtils.openInputStream(Mockito.any(File.class))).thenAnswer(invocation -> { File file = invocation.getArgument(0); return Files.newInputStream(file.toPath()); }); FileService fileService = mock(FileService.class); mockedFileServiceManager.when(FileServiceManager::getSystemFileService).thenReturn(fileService); assertThrows(NoClassDefFoundError.class, () -> seleniumAction.execute(driver, action, new HashMap<>(), new HashMap<>(), "AAA", "2000")); } } } 报错------------------------------------------------------------------------------- Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.570 s <<< FAILURE! -- in com.huawei.gts.testexecutor.util.SeleniumActionTest com.huawei.gts.testexecutor.util.SeleniumActionTest.testGetWebDriver -- Time elapsed: 0.010 s <<< ERROR! org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here: -> at com.huawei.gts.testexecutor.util.SeleniumActionTest.lambda$testGetWebDriver$0(SeleniumActionTest.java:55) -> at com.huawei.gts.testexecutor.util.SeleniumActionTest.lambda$testGetWebDriver$0(SeleniumActionTest.java:55) You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(any()); verify(mock).someMethod(contains("foo")) This message may appear after an NullPointerException if the last matcher is returning an object like any() but the stubbed method signature expect a primitive argument, in this case, use primitive alternatives. when(mock.get(any())); // bad use, will raise NPE when(mock.get(anyInt())); // correct usage use Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode(). Mocking methods declared on non-public parent classes is not supported. at com.huawei.gts.testexecutor.util.SeleniumActionTest.testGetWebDriver(SeleniumActionTest.java:55) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
11-04
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值