0

I have a class, which requires testing of some of its internal functions.

I do not want to embed these tests as part of the class, because they should be used only by some external entity whose sole purpose is system verification.

My solution to this comes in the form of declaring those internal functions protected, and add a class which "exposes" them for external usage.

Here is a very simple (pseudo-code) example:

class public MyClass {

    protected int add(int val1, int val2) {
        return val1 + val2;
    }

    protected int mul(int val1, int val2) {
        return val1 * val2;
    }
}

class MyClassExposurer : public MyClass {

    public int addTest(int val1, int val2) {
        return super.add(val1, val2);
    }

    public int mulTest(int val1, int val2) {
        return super.mul(val1, val2);
    }
}

Is there a known terminology for this design pattern?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • There is no point in testing private or protected methods. because they will automatically get tested when you are testing public methods. – Binary Baba Dec 14 '17 at 10:37
  • 1
    @RickSanchez: There is, because I want to pinpoint a problem, if such one exists. This problem may be "well hidden" when I run the external functions. – goodvibration Dec 14 '17 at 10:46
  • You can use reflection. – Binary Baba Dec 14 '17 at 10:52
  • @RickSanchez: My current implementation (similar to the coding example above) works just fine. Is reflection a better approach, or is it the actual terminology that I should use as the naming convention in my implementation? – goodvibration Dec 14 '17 at 11:18
  • Exposing a class just to test private methods is definitely not recommended. Check for annotation @VisibleForTesting if you are using JUnit, or for reflection, read this https://stackoverflow.com/a/34658/1749223 – Binary Baba Dec 14 '17 at 11:35
  • https://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes – jaco0646 Dec 14 '17 at 15:01

1 Answers1

0

You are looking for a name for the "design pattern" you use : i would say a mix between adapter and proxy. It works and can be left as is imo.

What bothers me more is that with that solution you are forced to dupplicate a class only to change the level of exposure while you could have considered using the keyword friend to allow your test class to access the private methods directly with the additional advantage of not modifying the initial level of encapsulation of the tested class (private).

floppy12
  • 1,045
  • 6
  • 12