Output is null в JUnit

при создании теста столкнулся с проблемой считывания строки с консоли.

Медот который тестирую:

public void run() {
        if(!isMove) {
            System.out.printf("%s run...", carName);
            isMove = true;
        } else {
            System.out.printf("%s is already running", carName);
        }
    }

Сам тест:

@Test
    public void testCarRunIsCarStop() {
        Cabrio cabrioTest = new Cabrio("TestName", "testBrend", false);

        cabrioTest.run();

        String template = "TestName run...";

        Assert.assertEquals(template, output.toString());
    }

After и Befor

    private ByteArrayOutputStream output;
    private PrintStream old;

    @Before
    public void setUpStreams() {
        old = System.out;
        output = new ByteArrayOutputStream();
        System.setOut(new PrintStream(output));
    }

    @After
    public void cleanUpStreams() {
        System.setOut(old);
    }

Вывод консоли:

TestName run...
java.lang.NullPointerException: Cannot invoke "java.io.ByteArrayOutputStream.toString()" because 
   "this.output" is null

at Cabrio.CabrioTest.testCarRunIsCarStop(CabrioTest.java:37)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at junit.framework.TestCase.runTest(TestCase.java:177)
at junit.framework.TestCase.runBare(TestCase.java:142)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:130)
at junit.framework.TestSuite.runTest(TestSuite.java:241)
at junit.framework.TestSuite.run(TestSuite.java:236)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:90)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

После изменения теста на:

  @Test
     public void testCarRunIsCarStop() {
        Cabrio cabrioTest = new Cabrio("TestName", "testBrend", false);
        
        output = new ByteArrayOutputStream();
        PrintStream stream = new PrintStream(output);
        System.setOut(stream);

        cabrioTest.run();
        String result = output.toString();

        String template = "TestName run...";

        Assert.assertEquals(template, result);
    }

Все отлично работает, не понимаю почему не работает в связке Befor-After


Ответы (0 шт):