Test Driven Development with C ++: how to test a class that depends on other classes?

Suppose I have a class A that depends on 3 other classes X, Y and Z, or A uses them with a reference or pointer, or say that A templated to create instances with X, Y and Z does not matter, the key is that for checking A I need to have X, Y and Z.

So, I need to have fakes for A, B, and C. Suppose I write them. Now, how can I easily exchange real and fake objects? I see that this works very easily with templates. To make it work when A depends on X, Y and Z with a reference or pointer, I need the base class to say X_Interface, from which I can inherit X_Real and X_Fake.

So basically, I get 3 times as many classes for every class that should have fake.

Most likely I'm missing something. There should be an easier way to do this. Having the X_Interface base class is also quite expensive since I will use more space and make virtual calls. I think I could use CRTP as I know if its X_Real or X_Fake at compile time, but there still needs to be a better way.

+3
source share
4 answers

First, make sure that the objects you depend on (X, Y, and Z) are passed in the constructor, so you can easily pass fakes when testing. (I really hope you use the unit test framework, for example CUnit)

, , , , "" , . "null", - "", ( , , ?)!

, .

, "", "", , .

.

GoogleTechTalks, .

+2

, unit test , , , , 3.

. , , . , :

  • , ? , 3 .

  • ( )? , .

  • ? .

, TDD . TDD . , . , , .

: , , .

+2

, . . SO .

+1
source

Unfortunately, in strong compilation languages ​​there are not many options. This is actually OK, because good architecture practice also encourages you to program for interfaces, not implementations. To minimize dependencies between modules / classes, you should have at least X_Interfaceand X_Real. In this case, good design and good testability go hand in hand. I suspect that many TDDs have indicated that this is exactly the point.

0
source

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


All Articles