JUnit断言两个字符串是否相等 [英] JUnit asserting two Strings whether they're equal or not

查看:689
本文介绍了JUnit断言两个字符串是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我查找了这个问题并尝试了一下,但没有成功.

So I looked up this question and tried it, but with no success.

我的代码应该通过使用Streams读回该文本来测试该方法是否正确地将文本输出到控制台上.

My code should be testing if the method is correctly outputing the text onto the console by reading it back in using Streams.

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    PrintStream myStream = new PrintStream(outStream);
    System.setOut(myStream);
    o.doSomething(); //printing out Hi
    System.out.flush();
    System.setOut(savedOldStream);//setting it back to System.out
    assertEquals(outStream.toString(),"Hi");

但是每次我运行JUnit都会失败. 我也尝试过:assertTrue(outStream.toString().equals("Hi"));但这也不起作用.

but everytime I run JUnit it fails. I also tried: assertTrue(outStream.toString().equals("Hi")); but this didn't work either.

这是doSomething()方法:

This is the doSomething() method:

public void doSomething () {
    System.out.println("Hi");
}

推荐答案

PrintStream#println(String str)在字符串末尾添加换行符.因此,您的主张应精简额外的一行:

PrintStream#println(String str) appends a newline at the end of the string. Therefore, your assertion should trim down the additional line:

assertEquals(outStream.toString().trim(),"Hi");

这篇关于JUnit断言两个字符串是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆