Junit Testing Void Methods

JUNIT testing void methods

I want to make some unit test to get maximal code coverage

Code coverage should never be the goal of writing unit tests. You should write unit tests to prove that your code is correct, or help you design it better, or help someone else understand what the code is meant to do.

but I dont see how I can test my method checkIfValidElements, it returns nothing or change nothing.

Well you should probably give a few tests, which between them check that all 7 methods are called appropriately - both with an invalid argument and with a valid argument, checking the results of ErrorFile each time.

For example, suppose someone removed the call to:

method4(arg1, arg2);

... or accidentally changed the argument order:

method4(arg2, arg1);

How would you notice those problems? Go from that, and design tests to prove it.

How to unit test a method which calls a void method?

You use the verify method:

verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));

In Java, How to test void method in Junit Mockito with assertion?

You need to capture the value passed to the dao save method. Use mockito's ArgumentCaptor for that. Then assert on that value.
Something along these lines:

ArgumentCaptor<Detail> captor = ArgumentCaptor.forClass(Detail.class);
verify(dyDBDAO, times(2)).save(captor.capture());
Detail detail1 = captor.getValues().get(0)
assertEquals(expectedDetail, detail1)

How to Test Void Method With No Arguments That Prints Line to Console

You can use System.setOut(PrintStream) to temporarily replace standard out with an in memory PrintStream backed by a ByteArrayOutputStream and use that to get the output. Something like,

@Test
void testLaunch() {
PrintStream original = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream tps = new PrintStream(baos);
Bird myBird = new Bird("Macaw");
System.setOut(tps);
myBird.launch();
System.setOut(original);
tps.flush();
assertEquals("Flapping the wings to take-off", baos.toString());
}


Related Topics



Leave a reply



Submit