search the lab

Embedded Testing with Unity & CMock (by Mark)

Embedded Testing with Unity & CMock

James Grenning's book (features Unity)

Test Driven Development for Embedded C

Topics

« Ceedling Intro | Main | CException Intro »
Wednesday
Feb162011

CMock Intro

What is CMock?

CMock is a module/object mocking framework for C projects useful for interaction-based unit testing. CMock uses Ruby to auto-generate C source code mock object modules conforming to the interfaces specified in C header files. It searches your header files for function declarations

ARGS* ParseStuff(char* Cmd);
void  HandleNeatFeatures(NEAT_FEATURE_T NeatFeature);

and creates a set of Mock objects and helpers

  int  ParseStuff(char* Cmd);
  void ParseStuff_ExpectAndReturn(char* Cmd, int toReturn);
  void ParseStuff_IgnoreAndReturn(int toReturn);
  void ParseStuff_StubAndCallback(CMOCK_ParseStuff_CALLBACK Callback);

  void HandleNeatFeatures(NEAT_FEATURE_T* NeatFeature);
  void HandleNeatFeatures_Expect(NEAT_FEATURE_T* NeatFeature);
  void HandleNeatFeatures_ExpectWithArrays(NEAT_FEATURE_T* NeatFeature, 
                                           int NeatFeature_Depth);
  void HandleNeatFeatures_Ignore(void);
  void HandleNeatFeatures_StubAndCallback(CMOCK_HandleNeatFeatures_CALLBACK
                                          Callback);

which you can use to help write tests

  void test_MyFunc_should_ParseStuffAndCallTheHandlerForNeatFeatures(void)
  {
      NEAT_FEATURES_T ExpectedFeatures = { 1, "NeatStuff" };

      ParseStuff_ExpectAndReturn("NeatStuff", 1);
      HandleNeatFeatures_Expect(ExpectedFeatures);

      //Run Actual Function Under Test
      MyFunc("NeatStuff");
  }

for other modules

  void MyFunc(char* Command)
  {
    int ID;
    NEAT_FEATURES_T Neat;

    ID = ParseStuff(Command);
    switch(ID)
    {
      case 0:  
        HandleStupidFeatures();
        break;
      case 1:
        Neat.id = 1;
        Neat.cmd = Command;
        HandleNeatFeatures(Neat);
        break;
      default:
        break;
    }
  }