我正在编写一个服务,用于向菜单中添加新的菜单项。在指导如何在Junit测试中模拟www.example.com的教程中,一切都工作正常System.in。但是,菜单项的一个参数需要设置为浮点值,即菜单项价格。因此,我通过ByteArrayInputStream和System.setIn提供的字符串输入似乎没有像我预期的那样将字符串值更改为浮点值。
这是我的服务代码:
public class DailyMenuServicesImpl implements DailyMenuServices {
private MenuPrinter menuPrinter;
public DailyMenuServicesImpl(){
this.menuPrinter = new MenuPrinterImpl();
}
@Override
public DailyMenu addMenuItemsToMenu(DailyMenu dailyMenu) {
Scanner scanner = new Scanner(System.in);
MenuItem menuItem = new MenuItem();
List<MenuItem> menuItemList = dailyMenu.getMenuItemList();
try {
System.out.print("\nInsert menu item name: ");
menuItem.setNames(scanner.nextLine());
System.out.print("Insert menu item description: ");
menuItem.setDescription(scanner.nextLine());
System.out.print("Insert menu item image: ");
menuItem.setImage(scanner.nextLine());
System.out.print("Insert menu item price:");
menuItem.setPrice(scanner.nextFloat()); // this is the problem everything above works fine.
menuItemList.add(menuItem);
dailyMenu.setMenuItemList(menuItemList);
}catch (IllegalStateException exception){
System.out.println(exception.getMessage());
}catch (InputMismatchException exception){
System.out.println(new InputMismatchException("Menu item price must be number !!!").getMessage());
}
return dailyMenu;
}
}
这是我的单元测试:
@RunWith(MockitoJUnitRunner.class)
public class DailyMenuServiceTest {
private MenuPrinter menuPrinter;
private DailyMenuServices dailyMenuServices;
private final InputStream systemIn = System.in;
private final PrintStream systemOut = System.out;
private ByteArrayInputStream testIn;
private ByteArrayOutputStream testOut;
@Before
public void init(){
dailyMenuServices = new DailyMenuServicesImpl();
testOut = new ByteArrayOutputStream();
menuPrinter = new MenuPrinterImpl();
System.setOut(new PrintStream(testOut));
}
@After
public void restoreSystemInputOutput(){
System.setIn(systemIn);
System.setOut(systemOut);
}
@Test
public void whenAddNewMenuItemsToMenu_returnNewDailyMenu(){
List<MenuItem> menuItemList = new ArrayList<>();
DailyMenu dailyMenu = new DailyMenu(menuItemList);
provideInput("Pizza\nGood\nItaly\n4.56f");
dailyMenu = dailyMenuServices.addMenuItemsToMenu(dailyMenu);
menuPrinter.printMenu(dailyMenu);
String expected = "Names: Pizza - Price: 4.56$";
assertEquals(expected,testOut.toString());
}
private void provideInput(String data){
testIn = new ByteArrayInputStream(data.getBytes());
System.setIn(testIn);
}
那么,如果我使用ByteArrayInputStream之类的教程,我如何将菜单项价格参数设置为浮点值呢?你的所有支持对我都有很大的帮助。
1条答案
按热度按时间rmbxnbpk1#
我相信你可以使用系统规则来传递来自Java.lang.System的用户输入。你可以在这里找到更多的信息:https://stefanbirkner.github.io/system-rules
请记住,这是一个外部库
语法应为
第一个