3

I am using Catch2 and I am trying to build a test case which does a complicate setup before the sections, represented in the listing by the initialization of a MyObject instance.

I like the idea of sections, since they keep the tests separated, but I would like to avoid the initialization of MyObject before every Section, is it possible?

TEST_CASE("Example"){

  MyObject obj{param1, param2}; /* This takes time! */

 SECTION("Check 1"){
    REQUIRE(obj.foo() == 42);
  }  

  SECTION("Check 2"){
     REQUIRE(obj.bar() == 58);
  }

}
NotMe
  • 65
  • 5
  • Can't you make ```obj``` global? – Melon Mar 18 '20 at 10:18
  • 2
    That would be an option, but I would rather not use globals. I was hoping catch had had a different section flavour to allow for this. – NotMe Mar 19 '20 at 11:45
  • If the setup/initialization is complicated, maybe you should refactor the code and move the time consuming part into a seperate function that you only call when you need it. Some people argue on initialisation you should only allocate the memory for you object, because if you crash in the c-tor, you might have allocated memory that doesn't get deallocated again i.e. a memory leak. – AudioDroid Jul 18 '22 at 08:25
  • @AudioDroid The suggestion to move the time consuming part into a separate function likely does not help here. If this time consuming operation is needed to get a "fully constructed" `MyObject` instance anyway, it still needs to be called at some point before the individual sections are run. So, it will still be called two times (whether it is done implicitly twice by the setup as in op's code, or explicitly once in each of the two sections). – Ad N Jan 13 '23 at 17:15
  • @AdN You are right. My comment is not a solution. Since I am aware of that, I have not put it in the "answer" section. This is just a suggestion in other respects to what is being presented here/above. In short..."A constructor should not take much time." And yes, this doesn't solve the problem. – AudioDroid Jan 16 '23 at 14:05

0 Answers0