java - 如何为将输出打印到控制台的 void 函数编写 junit 测试用例

标签 java unit-testing testing junit automated-tests

<分区>

我有两个函数 addKeywords 和 search,它们的返回类型为 void,而 search 函数将结果打印到控制台。 这是代码

 void addKeywords(String video)throws IOException{


    InputStreamReader ip = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(ip);

    Integer previousVal=0;

    if(!videoKeyword.containsKey(video) && videoNames.contains(video)){
        videoKeyword.put(video,new HashSet<String>());
    }
    else if(!videoNames.contains(video)){
        System.out.println("Video is not a part of lookup");
    }

    System.out.println("Enter keywords for video");
    String keyword =br.readLine();

    if(!keywordLength.containsKey(video))
        keywordLength.put(video, 0);

    if((keywordLength.get(video)+keyword.length())<500){
        videoKeyword.get(video).add(keyword);
        previousVal=keywordLength.get(video);
        keywordLength.put(video, previousVal+keyword.length());
    }
    else{
        System.out.println("Maximum length exceeded for video "+ video);
    }
    if(!kewordVideo.containsKey(keyword)){
        kewordVideo.put(keyword,new HashSet<String>());
    }
    kewordVideo.get(keyword).add(video);
 }

 void search(String searchKey){
    for (Entry<String, HashSet<String>> entry : videoKeyword.entrySet()) {
        for (String s : entry.getValue()) {
            if (s.startsWith(searchKey)) {
                System.out.println(searchKey+" is mapped to "+entry.getKey());
                break;
            }
        }
     }
 }

我写过junit测试

 public class MyUnitTest extends CultureMachineAssignment {
      CultureMachineAssignment testObj =new CultureMachineAssignment();
      testObj.insertDataIntoSet();
      testObj.addkeywords("video1");

     @Test
     public void testVideo() {
        assertEquals("video1", testObj.search("abcd"));
    }
}

我遇到以下错误

Assert 类型中的方法 assertEquals(Object, Object) 不适用于参数 (字符串,无效)

  • 标记“video1”的语法错误,删除 这个 token
  • token 语法错误,放错地方 构造

我不确定这是否是为具有 void 返回类型的函数编写 junit 测试用例并将输出打印到控制台的正确方法。 有人可以告诉我正确的代码吗?

最佳答案

您可以使用 System.setOut(printStream) 和 System.setErr(printStream) 函数重定向 System.out 或 System.err 消息。
这样您就可以将 System.out 消息放入打印流对象中并可以读取它。

关于java - 如何为将输出打印到控制台的 void 函数编写 junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30475908/

相关文章:

java - 使用 Java Graphics2D 与 JOGL

java - 提取名称中未列出的嵌入文件

c# - DocumentDB 存储库单元测试

javascript - 然后没有触发 Jasmine 的提取模拟

ruby-on-rails - 使用遗留 Rails 应用程序

ruby-on-rails-3 - 为什么这个规范/ Controller 测试不通过?它以前做过......(Rails,RSpec)

Java:使用牛顿法多次平方根

java - Rhapsody API 重新加载项目

javascript - Jest 中的嵌套模拟函数

python - 我可以通过 Python 中的 splinter 模块以某种方式从页面上的下拉列表中选择特定元素吗