2. Unit testing advanced

There can be cases where the task at hand is not as easy as it is with sample_1. One of the cases is when exceptions are at play. Take a look at the next example that we will go through here sample_2. Our first CUT will be Hellolink.java and let’s take a look at its implementation

Supporting video

Example 1

One of our main goal here is to reach a high level of coverage, therefore we would like to test most of the functions. If we take a look at public int multiply(int aLeft, int aRight) how do we actually test such a function and assure that it will give us the correct results in all circumstances. Testing all the different numbers in the int type would take years, therefore there should be some other technique that we can apply to do testing on this function. Otherwise, implementing the test of each individual number for the int type would result in multiple millions lines of code, which is unmaintainable. To overcome these problems, one can apply the parameterized tests to handle the different cases from a small sized code. The solution goes as follows

  • The test function shall be annotated by the @ParameterizedTest annotation, where additionally the framework needs data to feed to the test function, which can be approached with @CsvSource annotation.

Tasks 1

  1. Run the sample_2 and inspect the report
  2. Check what is wrong with public void numeric_test(int left, int right)
  3. Implement the missing functionality in Hellolink.java

Supporting video

Example 2

It is good to have some sufficient numerical tests, but there are other functionalities that need some check-ups. One of the main issues with Hellolink.java is that, it exposes a constructor, which initializes a vector with a certain amount of parameters. Later on this could be a problem, since nobody assures that the users of our code won’t access out of bounds elements of our vector, which should be handled inside our functions. To do this, one can implement the public void IndexOutOfBoundsTest() function, which does that exactly. This function is simple, it initializes a local variable of our Hellolink.java class and then asserts against if the access of that vector raises an exception with the help of assertThrows.

There can be cases, when during TDD one implements the tests first, but softly doesn’ want them to fail at first. This goal can be achieved by simply putting the @Disabled annotation with a reasonable message in the test cases.

Sometimes the timing of the test running is important, therefore one needs to put certain blocks on the execution of test functions. This can be done by annotating, the test case with @Timeout(NUM), where NUM is the number if milliseconds that the test will be blocked.

Tasks 2

  1. Try to write a test such that, public int multiply(int aLeft, int aRight) throws an exception
  2. Write a test such that certain cases inside the parameterized tests will be disabled