gpt4 book ai didi

java - 使用 JUnit 测试函数,其中函数获取用户输入

转载 作者:行者123 更新时间:2023-12-01 21:41:45 26 4
gpt4 key购买 nike

首先,我尝试在这个很酷的网站中寻找一些解决方案。我发现了与我的问题相关的问题,但我的测试仍然失败。我发现的问题可以在这里找到:JUnit testing with simulated user input

让我们看看我的实现:

我有一个用户交互服务类,它读取然后验证用户输入:UserInteractionService.java

package Services;

import java.util.Scanner;

public class UserInteractionService {

private static Scanner scanner = new Scanner(System.in);

public static int readIntegerAndValidate() {
while (!scanner.hasNextInt()) {
System.out.println("It is not a valid integer number. Try again!");
scanner.next();
}
return scanner.nextInt();

}

public static double readDoubleAndValidate() {
while (!scanner.hasNextDouble()) {
System.out.println("It is not a valid number. Try again!");
scanner.next();
}
return scanner.nextDouble();
}
}

当然,我有一个针对该服务类的测试类:UserInteractionServiceTest.java

@Test
public void userWriteInput_checkIfItIsInteger_userTypedInteger() {
String inputData = "5";
System.setIn(new ByteArrayInputStream(inputData.getBytes()));
int input = readIntegerAndValidate();
assertEquals(5, input);
}

@Test
public void userWriteDouble_checkIfItIsDouble_userTypedDouble() {
String inputData = "5.3";
System.setIn(new ByteArrayInputStream(inputData.getBytes()));
double input = readDoubleAndValidate();
assertEquals(5.3, input, 0);
}

好吧,我的第二个测试函数(userWriteDouble_checkIfItIsDouble_userTypedDouble)失败了,我找不到原因......正如你所看到的,我使用了与第一个测试中相同的模式。您的意见是什么?为什么此测试失败?我应该使用一些模拟框架(Mockito)吗?预先感谢您的回答!

故障追踪:

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Services.UserInteractionService.readDoubleAndValidate(UserInteractionService.java:21)
at Services.UserInteractionServiceTest.userWriteDouble_checkIfItIsDouble_userTypedDouble(UserInteractionServiceTest.java:23)
...

最佳答案

通过将扫描器设置为静态,您使测试代码变得更加困难。我会考虑给 UserInteractionService 一个带有 Scanner 的构造函数。我建议 EasyMock ,测试中的代码看起来像

import static org.easymock.EasyMock.*;

Scanner scanner = createMock(Scanner.class);
expect(scanner.hasNextDouble()).and return(true).once();
expect(scanner.nextDouble()).and return(5.3).once();

replay(scanner);

您在测试中调用的服务将是

new UserInteractionService (scanner)

关于java - 使用 JUnit 测试函数,其中函数获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com