gpt4 book ai didi

java - 尝试使用 Junit 验证控制台输出与字符串匹配

转载 作者:行者123 更新时间:2023-11-30 01:54:56 36 4
gpt4 key购买 nike

我正在尝试使用 Junit 来验证方法输出的内容是否与使用 assertequals 的字符串匹配,但我无法让它工作。因为它说测试用例未定义 (String, Void) 我的方法代码如下

public void speciesInformation() {
switch (species){

case"Penguin":System.out.println("Penguin Trivia fact");
break;

default: System.out.println("There is no current information for that species");
break;
}
}

我尝试使用的junit代码是(省略其他测试):

public class AnimalsTest extends junit.framework.TestCase{
public void testSpeciesInfo() {
assertEquals(" Penguin Trivia fact/n", penguin.speciesInformation());
}
}

我的所有其他测试都有效,因为它们基于返回,但这个测试应该基于 public void 方法打印的内容,我不知道如何做或找到有关如何做的信息。

最佳答案

您可以使用ByteArrayOutputStream来实现此目的,在System.setOut中设置byteArrayOutputStreamnew PrintStream,然后您可以轻松断言控制台中记录的内容。

See this for example

关于java - 尝试使用 Junit 验证控制台输出与字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837911/

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