我创建了一些设置字符串、获取字符串和获取元音的方法,如下所示。如何为 getVowels()
编写 JUnit 测试用例?
在测试用例中,我不应该说明正确答案是什么吗?既然用户可以输入任何字符串,那么如何让 Junit 通过或失败测试用例呢?在测试用例的最后一行中,我应该在 assertEquals
中输入什么?
package sec.vowels;
import java.util.Scanner;
public class MyStrings implements MyStringInterface {
public String str;
public char c;
// Sets the value of the current string
public void setString(String str) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a sentence:");
str = input.next();
input.close();
System.out.println(str);
}
// Returns the current string
public String getString() {
return str;
}
public String getVowels(){
for (int i=0; i <str.length();i++){
c = str.charAt(i);
if((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u')){
}
System.out.println(c);
}
return str;
}
}
//test case.
public void testGetVowels() {
MyStrings test = new MyStrings();
String results = test.getVowels();
assertEquals("");
最佳答案
IMO,您的 setString()
在一个方法中执行了太多任务。这可能是您在测试时遇到困难的原因之一。就我个人而言,我会将其重写为
public void setString(String str) {
this.str = str;
}
现在setString()
并不关心String
来自哪里。在 JUnit 测试中,您可以使用固定的字符串文字。在交互式程序中,main()
可以向用户询问一个字符串(类似于您现在的操作方式),然后将其传递给 setString()
。
这种解耦在许多情况下都是理想的。
另一个建议是用 c
替换对 str.getCharAt(i)
的重复调用,因为您已经将该结果存储在变量中。此外,c
应在 getVowels()
本地声明,因为它未在任何其他方法中使用。
关于java - 用于返回用户输入字符串中的元音的 Junit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634898/