Testing of this method was called

Very simple class:

public class ConsoleHandler {

    public void write(String message) {
        System.out.println(message);
    }

}

How to check when a call write("hello")is invoked System.out.println("hello")? And also, is this unit test even worth it?

+4
source share
4 answers

As for whether to test, it depends on why you output. I usually test calls to System.out when writing command line utilities because it is a user interface and text output. It’s not even hard to do - just plain Java code.

System.out. . , "" System.out, . , / .

import static org.junit.Assert.*;

import java.io.*;

import org.junit.*;

public class ConsoleHandlerTest {

    private PrintStream originalSysOut;
    private ByteArrayOutputStream mockOut;

    @Before
    public void setSysOut() {
        originalSysOut = System.out;
        mockOut = new ByteArrayOutputStream();
        System.setOut(new PrintStream(mockOut));
    }

    @After
    public void restoreSysOut() {
        System.setOut(originalSysOut);
    }

    @Test
    public void outputIsCorrect() {
        new ConsoleHandler().write("hello");
            assertEquals("message output", "hello".trim(), mockOut.toString().trim());
    }

}
+4

, unit test . - , . , . .

unit test , , . , , , . , X Y, - .

, , System.setOut, ByteArrayOutputStream, PrintStream, byte[] .

+2

, Mockito (http://code.google.com/p/mockito/), , .

, Sysout . , Log4J , SLF4J (http://www.slf4j.org/). SLF4J , (http://projects.lidalia.org.uk/slf4j-test/)

, , JUnit TestNG .

0

" , write (" hello ") System.out.println(" hellow ")?

Mockito : Mockito: how , ?

" unit test ?" , , . , , - .

0

Source: https://habr.com/ru/post/1541982/


All Articles