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
Eclipse Will Not Open Due to Environment Variables
How to Deserialize a List Using Gson or Another JSON Library in Java
How to Get the Count of Line in a File in an Efficient Way
Spring Session-Scoped Beans (Controllers) and References to Services, in Terms of Serialization
How to Convert a Hexadecimal String to Long in Java
How to Create an 2D Arraylist in Java
Are There Any Other Java Libraries for Bonjour/Zeroconf Apart from Jmdns
How to Open a Txt File and Read Numbers in Java
In Java, When I Call Outputstream.Close() Do I Always Need to Call Outputstream.Flush() Before
Why Does Java Switch on Contiguous Ints Appear to Run Faster with Added Cases
Java:Does Wait() Release Lock from Synchronized Block
How to Implement Infinity in Java
Print Full Call Stack on Printstacktrace()