How do you develop a C ++ application to make Mock Objects the easiest to use?

I never developed using Test Driven Development, and I never used Mock Objects for unit testing. I always tested simple objects that did not include other aspects of the application, and then moved on to less simple objects that only reference objects that have already been tested. This tends to develop until the final “single” test is tested by the component.

What design methods are used to facilitate the replacement of inner classes with Mock Objects?

For example, in my code, I would include the header file for myDataClass in myWorkerClass. myDataClass is built by myWorkerClass, and its lifetime is tied to myWorkerClass. How can you configure it to include mock myDataClass when include is hard?

+3
source share
3 answers

You can see how to adapt your code to follow the Factory Design pattern (Annotation) , which may result in another Factory used in the unit test environment that will create your mock objects.

+2
source

The newcomers answer will be as follows:

  • the test class does not use the actual type of bullying, use its interface
//Common header
class ObjectInterface {
public:
  virtual void doThings()=0;
};

//Release
class RealObject: public ObjectInterface {
public:
  virtual void doThings(){
    //Complicated work here
  }
};

//Testing 
class MockedObject: public ObjectInterface {
public:
  virtual void doThings(){
    //Not so complicated work here
  }
};

//Common header
class TestedClass {
public:
  void useObject(ObjectInterface & object) {
    object->doThings();
  }
};


//Unit test
TestedClass toTest;
MockedObject mockedObject;
toTest.useObject(mockedObject);
+4

, .

:

myDataClass . 2 , "" .

mock 2 , "myDataClass", - . . .

class myWorkerClass {
public:
    myWorkerClass(myDataClass * dc) : m_dc(dc) {}
    myWorkerClass() : m_dc(new MyRealDataClass()) { }
    ~myWorkerClass { delete m_dc; }

private:
    myDataClass *m_dc;
}

myDataClass myWorkerClass, . , "" .

Another method would be to use the Factory pattern to instantiate your objects. Your test code could set some flag in Factory, which creates instances of myDataClass and creates a mock object for it instead of the real one. I prefer the first technique, as it’s a little easier for me to use (plus I don’t need to support the Factory class for everything I want to check)

0
source

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


All Articles