Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing classes

I put together a class yesterday to do some useful task. I started alpha testing, and at some point realized I was adding alpha test related methods to the class itself. It hit me that they don't belong there. After a bit of head scratching I derived a test class from the base class that has access to the protected members as well. I put all of the testing related methods, and set up and tear down in the test class, and left the base class lean and mean as the old saying goes.

After browsing around here awhile I found one comment that suggested using this sort of technique by making the testing class a friend of the real class.

In retrospect both of those techniques should have been obvious to me.

What I am looking for, are techniques for specifically alpha testing/unit testing classes, without adding to the weight of the class being tested.

What techniques have you personally used, and recommend?

like image 328
EvilTeach Avatar asked Dec 22 '22 13:12

EvilTeach


2 Answers

One of the goals of unit testing is to verify the interface to your classes. This means that, generally speaking, you shouldn't be testing the dirty innards of your class. The unit test is supposed to interact with the public inputs and outputs of your class, and verify that the behaviour is as expected. You are thus able to change the internal implementation of your class without affecting all of the other objects that depend on it. Obviously, I don't know the details in your situation but I would say that, as a general rule, if your unit test is trying to figure out the private details of the class, you are doing something wrong.

edit: See also: This SO question. Notice that it can be done (top answer), but also notice that the second-place answer (by a short margin) says more or less the same thing as I mention above.

like image 84
e.James Avatar answered Jan 01 '23 16:01

e.James


It sounds like you don't want Unit testing, which is correctly the verification that the interface of a class works. You shouldn't have to change your class at all in order to do unit testing. If you are looking for a way to verify the internal state of your object so that it remains consistent, you should look into Design by Contract methods, which can verify internal state from within the object.

like image 29
jamuraa Avatar answered Jan 01 '23 16:01

jamuraa