Am I unit testing correctly?

Hi

I am currently writing some unit tests for a library which I've written. As an example, say I'm testing a particular a method called doSomething() then my test structure would be something like as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  // test.cpp
  bool doSomething_whereXisCase_shouldDoThingP() {
  
  if (!testSomething()) 
      return false; // test 1 failed

  if (!testSomethingElse())
      return false; // test 2 failed
  
  return true;
  }


  bool doSomething_whereYisCase_shouldDoThingQ() {
     
  if (!testSomething()) 
      return false;

  if (!testSomethingElse())
      return false;
  
  return true;
  }
  
  // main.cpp
  test_doSomething() {
     assert (doSomething_whereXisCase_shouldDoThingP());
     assert (doSomething_whereYisCase_shouldDoThingQ());
  }


Is this a typical approach? Or should I be asserting in each method e.g.:

1
2
3
4
5
6
7
8
9
10
11
12
  // test.cpp
  void doSomething_whereXisCase_shouldDoThingP() {
  
     assert (testSomething()); 
     assert(testSomethingElse());
  }

  // main.cpp
  test_doSomething() {
     doSomething_whereXisCase_shouldDoThingP();
     doSomething_whereYisCase_shouldDoThingQ();
  }


Perhaps the second approach is better as the assert is more granular and so it will be easier to tell exactly where the error occurred? Any thoughts much appreciated.

Thanks
Last edited on
Have you considered pre-existing frameworks like say http://cppunit.sourceforge.net/doc/cvs/index.html
Perhaps the second approach is better as the assert is more granular and so it will be easier to tell exactly where the error occurred?
Why not both. There is always the chance that all the details seem to be okay but the result is still not okay.
Find the happy medium that gets you to where the error is found.

One way to do it: if you are testing a function, and it gives the wrong answer, if its calls other functions, you unit test those next. If those call more functions, you unit test those ... and so on down the chain until you hit the end of the tree where the functions do something and return. Each function should have a test. If none of the functions fail their tests, the top level one should be the problem or your unit tests are no good.

You can do this with some smarts, though. You can filter the above using your source control to only test what changed since the last time everything worked.
Last edited on
Topic archived. No new replies allowed.