我在春季曾进行过junit测试集成测试和控制器测试,通常我们会测试方法的输出,但是当我尝试在main方法中测试一个简单的hello世界时,我不知道如何进行操作,因此希望获得任何方法关于写什么的想法
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
Run Code Online (Sandbox Code Playgroud)
这是简单的Java类,我知道如何测试它,我试图写这样的东西
public void mainMethodTest() throws Exception{
System.out.println("hello world");
String[] args = null;
Assert.assertEquals(System.out.println("hello world"),App.main(args));
}
Run Code Online (Sandbox Code Playgroud)
您可以为System.out变量分配一个ByteArrayOutputStream对象,该对象将引用存储在变量中。
然后调用您的main()方法,并断言String该ByteArrayOutputStream对象的内容包含预期的内容String:
@Test
public void main() throws Exception{
PrintStream originalOut = System.out; // to have a way to undo the binding with your `ByteArrayOutputStream`
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
// action
App.main(null);
// assertion
Assert.assertEquals("hello world", bos.toString());
// undo the binding in System
System.setOut(originalOut);
}
Run Code Online (Sandbox Code Playgroud)
为什么行得通?
bos.toString()返回"Hello World!" String在测试中传递的方法:
System.out.println( "Hello World!" );
Run Code Online (Sandbox Code Playgroud)
像在System.out以这种方式设置之后: System.setOut(new PrintStream(bos));,out变量指的PrintStream是装饰该变量引用的对象的ByteArrayOutputStream对象bos。因此,任何System.out调用都会byte在ByteArrayOutputStream对象中写入。
你可以这样改变你的班级
import java.io.PrintStream;
public class TestHelloWorld {
public final static void main(String[] args) {
doPrint(System.out);
}
static void doPrint(PrintStream ps) {
ps.println("Hello World");
}
}
Run Code Online (Sandbox Code Playgroud)
并doPrint通过提供您自己PrintStream创建的功能来测试该功能ByteArrayOutputStream:
public void mainMethodTest() throws Exception{
ByteArrayOutputStream data = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(data, true, "UTF-8");
TestHelloWorld.doPrint(ps);
ps.flush();
Assert.assertEquals("Hello World") + System.getProperty("line.separator"), new String(data, "UTF-8"));
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是PrintStream用您自己的系统替换系统:
System.setOut(new PrintStream(data, true, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
但这很丑陋,我尽量避免这种情况。上述解决方案更清晰,更易于维护,您可以确保在您进行测试时,大型应用程序的其他部分不会向 STDOUT 打印某些内容,从而导致测试失败。
| 归档时间: |
|
| 查看次数: |
499 次 |
| 最近记录: |