如何为Person类的void类型showDataPerson()方法编写正确JUnit测试
Correct JUnit Test for Void
showDataPerson() Method Let's fix your test step by step. The core issue here is that showDataPerson() returns void—you can't pass a void method call directly to assertEquals(). To test what this method prints to the console, we need to capture the output from System.out and then assert it against our expected string.
Here's the revised test code with explanations:
import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.jupiter.api.Assertions.assertEquals; public class PersonTest { @Test public void testShowDataPerson() { // 1. Create your test Person instance Person test = new Person("Bill", "Cage", "JavaSeller SA", "567854367", "Address 1", "12-345 Warsaw", "23456789765456789098765456"); // 2. Save the original System.out stream to restore it later PrintStream originalSystemOut = System.out; ByteArrayOutputStream capturedOutput = new ByteArrayOutputStream(); // 3. Redirect System.out to our capture stream System.setOut(new PrintStream(capturedOutput)); try { // 4. Execute the method we want to test test.showDataPerson(); // 5. Convert captured output to a string String actualOutput = capturedOutput.toString(); // 6. Build the expected output string (matches exactly what showDataPerson() prints) String expectedOutput = "\n" + "Bill Cage\n" + "JavaSeller SA (nip: 567854367)\n" + "Address 1\n" + "12-345 Warsaw\n" + "Numer konta:\n" + "23456789765456789098765456\n" + "\n"; // 7. Assert the captured output matches our expectation assertEquals(expectedOutput, actualOutput); } finally { // 8. Always restore the original System.out to avoid breaking other tests System.setOut(originalSystemOut); } } }
Key fixes and explanations:
- Capturing console output: We use
ByteArrayOutputStreamto catch all data written toSystem.outwhenshowDataPerson()runs. This lets us convert the output to a string for assertion. - Restoring
System.out: We save the original stream and restore it in afinallyblock—this ensures other tests aren't affected by our output redirection. - Exact output matching: The
expectedOutputstring mirrors every line (including the leading and trailing empty lines) printed byshowDataPerson(), since eachSystem.out.println()adds a newline character.
Your original test failed because you tried passing a void method call to assertEquals()—this isn't allowed in Java, as void methods don't return a value to compare. The approach above solves that by capturing the side effect (console output) instead of trying to compare a return value.
内容的提问来源于stack exchange,提问作者pkucinski
相关产品推荐
相关产品推荐

