简体   繁体   中英

Method assertEquals(Object, object) in the type Assert is not applicable for the arguments (String, Void)

I have a static void method that prints out a statement depending on what string is input and then returns. I'm trying to use jUnit to make sure that the print statement is correct for the input given.

I tried to use assertEquals(expected, System.method("input"));

I am given the error "The method assertEquals(Object, object) in the type Assert is not applicable for the arguments (String, Void)." I understand the error, but I have been unable to find out how to write my test case differently so that I can compare the two.

To expand on @tradeJmark's answer; assuming your static method (the one to test) is calling System.out.print* for something; then you can 'hijack' the OutputStream for System via:

@Test
public void testThing() {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    System.setOut(new PrintStream(out));

    ClassToTest.testMethod(/* desired input */);

    final String written = out.toString();

    Assert.assertEquals(expected, written);
}

Noting of course things like calling System.out.println(...) (rather than System.out.print(...) ) will append \\n (or similar depending on OS) to the end of the written String , etc.

Note: If you're planning to do this; I'd recommend reverting it somewhere as well. Something like the following should handle this.

private static PrintStream ORIGINAL_OUT = null;

@BeforeClass
public static void interceptOut() {
    ORIGINAL_OUT = System.out;
}

@AfterClass
public static void revertOut() {
    System.setOut(ORIGINAL_OUT);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM