Sometimes, I encounter situations where all I need to test is whether the program's execution reaches a certain point without any exceptions being thrown or the program being interrupted or getting caught in an infinite loop or something.
What I don't understand is how to write a unit test for that.
For instance, consider the following "unit test" -
@Test
public void testProgramExecution()
{
Program program = new Program();
program.executeStep1();
program.executeStep2();
program.executeStep3();
// if execution reaches this point, that means the program ran successfully.
// But what is the best practice?
// If I leave it like this, the test will "pass",
// but I am not sure if this is good practice.
}
Usually, at the end of a test, I have a statement like-
assertEquals(expectedString, actualString);
But how to write an assertEquals or other type of test statement for the above case?
Unit testing may not be possible in all situations. When object-oriented software is considered, the concept of unit testing changes. Encapsulation drives the definition of classes and objects. This means that each class and each instance of a class packages attributes and the operations that manipulate these data.
Your code looks fine, just remove the comments, but leave this one:
// If execution reaches this point, that means the program ran successfully.
So readers of your code will understand why there are no assertions.
It is worth noting that every method called in your test should have some kind of effect, and that effect should be asserted as having happened correctly, even if you say "you don't care".
If you insist there is no need to check, add a comment to explain why - this will save readers from trawling through your code to find out for themselves why "it doesn't matter", for example:
// No assertions have been made here because the state is unpredictable.
// Any problems with execution will be detected during integration tests.
In situations like that I am just insert
assertTrue(true);
at the end of the function...
If the mere act of an exception not being thrown means the test has passed, you don't need any assertions. Admittedly that suggests that the action has no observable side-effects, which is somewhat rare. A comment would be more useful than an assertion in this case.
Usually I find this only happens when I've got other tests for checking the actual results, and some tests proving invalid input, and a few similar tests proving just about valid input. For example, if I wanted to validate that the input had to be in the range [0, 100]
I may well have "full" tests for a few medium values, then invalid values of -1 and 101, then valid values of 0 and 100 which just prove they're valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With