How detailed / granular should your tests be?

I recently started a new project in which I decided to accept written tests for most functions. Prior to this, my testing was limited to sporadically writing test "functions" to ensure that something works properly, and then never bother updating the test functions, which is clearly not good.

Now that I have written a lot of code and tests, I noticed that I am writing a lot of tests for my code. My code is usually quite modular, in the sense that I try to code small functions that make something simple, and then stick them together in a larger function as necessary, again, to adopt best practice.

But now I am finishing writing tests for both individual functions of the "building block" (rather small tests) and for tests for a function that combines them, as well as checking the results there, obviously, the result will be different, but since the inputs are similar, I I’m duplicating a lot of test code (setting up the input parts, which are slightly different from each other, but not much, since they are not identical, I can’t just use a text mount ..).

Another problem is that I try to strictly adhere to one test per test, so I write one test for each function inside the function, for example, if there is additional input that can be passed to the function, but which is optional, I write one version that adds input, one that does not execute and tests them separately. The setting here is again basically identical, except for the input that I added, again it’s not exactly the same, so using the device does not seem to be “correct”.

Since this is my first project with everything that has been fully tested, I just wanted to make sure that I was doing things right and that code duplication in tests was expected. Therefore, my question is: am I doing things right? If not, what should I change?

I am code in C and C ++.

On the side of the note, I love testing myself, I am much more confident in my code now.

Thanks!

+6
source share
1 answer

Your question is trying to solve many things, and I can try to answer only some of them.

  • Try to get the highest possible coverage (ideally 100%).
  • Do not use real resources for your unit test, or at least try to avoid it. You can use mocks and stubs for this.
  • Not unit test third-party libraries.
  • You can break up dependencies using dependency injections or functors. Thus, the size of your tests can be reduced.
+1
source

Source: https://habr.com/ru/post/892306/


All Articles