我正在測驗一個包含串列項的類。這些值是通過掃描儀從用戶輸入中插入的。我想在 add 方法之前測驗串列以檢查是否有空值。我正在向您提供我到目前為止所做的事情。我對 Spock 和 Groovy 完全陌生。
要測驗的類
package inventory;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Menu {
static Scanner scanner = new Scanner(System.in);
static ArrayList<Item> items = new ArrayList<>();
public static void printMenu(String[] options) {
for (String option : options) {
System.out.println(option);
}
System.out.print("Choose your option : ");
}
private static final String[] options = {
"1- Adding an Item ",
"2- Create and Print the Json file of Items",
"3- Create and Print the Html file of Items",
"4- Create and Print the Xml file of Items",
"5- Create and Print the Csv file of Items",
"6- Exit"
};
public static void addingItemsFromUserInput() {
int option = 1;
while (option != 7) {
printMenu(options);
try {
option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Please enter the Name of the Item: ");
String name = scanner.next();
System.out.print("Please enter the Serial Number of the Item: ");
String serialNumber = scanner.next();
System.out.println("Please enter the Item Value");
BigDecimal amount = scanner.nextBigDecimal();
Item item = new Item(name, serialNumber, amount);
addingAnItem(item);
break;
case 2:
TrackingFile tFileJson = new JsonFile(items);
tFileJson.createTheFile();
tFileJson.writingTheFile();
break;
case 3:
TrackingFile tFileHtml = new HtmlFile(items);
tFileHtml.createTheFile();
tFileHtml.writingTheFile();
break;
case 4:
TrackingFile tFileXml = new XmlFile(items);
tFileXml.createTheFile();
tFileXml.writingTheFile();
break;
case 5:
TrackingFile tFileCsv = new CsvFile(items);
tFileCsv.createTheFile();
break;
case 6:
scanner.close();
System.out.println("Have A Nice Day!");
return;
}
} catch (Exception ex) {
System.out.println("Please enter an integer value between 1 and " options.length);
scanner.next();
}
}
}
// Options
public static void addingAnItem(Item item) {
items.add(item);
}
public List<Item> getItems() throws RuntimeException {
if (items.contains(null)){
throw new RuntimeException("Name cannot be null");
}
return items;
}
}
實際測驗
def "cannot save if name is null"(){
given:
Menu menu = new Menu()
menu.items.contains(null)
when:
menu.getItems()
then:
RuntimeException e = thrown()
e.message == "Name cannot be null"
}
我收到以下堆疊跟蹤。可以請有人幫助我,克服這個。
'java.lang.RuntimeException' 型別的預期例外,但未引發例外 'java.lang.RuntimeException' 型別的預期例外,但在 org.spockframework.lang.SpecInternals.checkExceptionThrown(SpecInternals.java:81 ) at org.spockframework.lang.SpecInternals.thrownImpl(SpecInternals.java:64) at inventory.MenuSpec.cannot save if name is null(MenuSpec.groovy:55)
uj5u.com熱心網友回復:
given:
Menu menu = new Menu()
menu.items.contains(null)
contains不修改串列,只回傳真/假。從不使用回傳值。
您確實想將專案添加到串列中,而不是檢查它是否存在(不是,您從未添加過它):
given:
Menu menu = new Menu()
menu.items.add(null)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/510524.html
標籤:爪哇单元测试测试斯波克
