Junit测试预期和实际

时间:2019-01-21 21:22:50

标签: junit4 system-rules

I have problem与此相关,我不知道如何解决。

这是我的课程:

import java.util.Scanner;

public class ScannerAndKeyboard
{

    public static void main(String[] args)
    {   Scanner s = new Scanner(System.in);
        System.out.print( "Enter your name: "  );
        String name = s.nextLine();
        System.out.println( "Hello " + name + "!" );
    }
}

这是我的JUnit测试

public class ScannerAndKeyboardTest {

    @Rule
    public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();

    @Rule
    public final SystemOutRule OutLog = new SystemOutRule().enableLog();

    @Test
    public void Name() {
      String name = "Name";
      String expectedConsoleOutput = "Enter your name: Hello Name!" + System.lineSeparator();
      systemInMock.provideLines(name);

      ScannerAndKeyboardTest.main(new String[] {});

      Assert.assertEquals(expectedConsoleOutput,OutLog.getLog());
    }

    private static void main(String[] strings) {
    }
}

这是第31行

Assert.assertEquals(expectedConsoleOutput,OutLog.getLog());

有人可以告诉我即时消息做错了什么,为什么此日志为空?我迈出了第一步

1 个答案:

答案 0 :(得分:0)

问题是您调用了错误的main方法。替换

ScannerAndKeyboardTest.main(new String[] {});

ScannerAndKeyboard.main(new String[] {});

您还应该删除方法ScannerAndKeyboardTest#main,因为它不是必需的,只会引起混乱。

如果将main方法的签名更改为

public static void main(String... args)

那么您不必在测试中创建一个空数组,就可以简单地调用

ScannerAndKeyboard.main();