Unit Testing C ++ 11 Closures

Is there any priority for unit testing when closing C ++?

The functions that I write usually begin as closures, defined near their point of use, and then (possibly) after the end of the final functions. This is good for keeping interfaces clean and easier to read in a linear fashion, but it undermines written tests.

Are there any tricks or structural C ++ modulation modules that can handle, say, a small function to calculate some geometry, which is defined as a closure inside my main ()?

+5
source share
3 answers

I would think you should test functions, not lambda functions. If a function contains lambda functions, then these are implementation details. If you reuse lambda functions by creating them as variables, then they are easily checked by the module as functions.

Eg.

auto lambda = [](/* params */){/* stuff */}; // this can be unit tested void func() // this can be unit tested { // the lambda is an implementation detail of the function sort(/* stuff */, [](/* params */){/* stuff */}); } 
+5
source

TL DR: Nope.

To close the unit test, you will need to give it a name that you can refer to by assigning it to a variable.

If it is difficult enough for the unit test yourself, you should extract the method and verify this.

Other than this, you can always close the unit test indirectly through a method or function that contains it.

+2
source

In short, no. but..

You can check the code that uses closure. The fact that closures are built into the source code and you don’t have any reflection mechanism does not allow you to test them for unity (however, you have many ways to check the material, not just unit tests), however, as a rule The code using closures is more compact, so while we are testing the whole block with closures, it’s good to use them. I tend to write a closure that is just a few lines of code, infact, you could actually create a function (called a closure) and unit test the function itself;).

 int function(MyClass *){ // unit test here } //... void MyClass::method(){ // ... and unit test method auto f = [this] () { return function(this);}; applyFunctorOnCollection(f); } 
+1
source

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


All Articles