No, you don't have to understand every line of code to write Unit tests. I'm not so experienced with unit tests yet, but what if seen so far is testing every (or most) methods that respond differently to a certain input (--> arguments, object variables ...).
So you have to know what a method does, when it successfully does things, and when it is suppose to fail. And for some methods even the turning points between those cases are important.
For Example
Let's say we have a method that sums two ints, that have to be equal to or larger than 0:
public static int sumInts(int a, int b) {
if (a < 0 || b < 0) throw new IllegalArgumentException("'a' and 'b' should be 0 or above!");
return a + b;
}
What you could test:
- if a = 49 and b = 16, does it return 65?
- if a = -3 and b = 4, does it throw an exception?
- if a = 5 and b = -13, does it throw an exception?
- if a = -46 and b = -13, does it throw an exception?
- if a = 0 and b = 0, does it return 0?
- if a = -1 and b = -1, does it throw an exception?
Of course, this is just a very simple example. What you test depends on your method. For this method, the last two tests would likely be totally unneeded. But there are methods that are more complex, where those could be useful.