Creating new constructors to overwrite the existing instance variables for testing purpose

by isqo   Last Updated November 08, 2018 23:05 PM

Is it good/bad practice to add more constructors just for test purposes (to mock the DOCs used in my SUT) like this :

public class A {
    private B b = new B();
    private C c = new C();

    public A(){
    }

    /***
     * used for test puproses
     * @param a
     * @param b
     */
    A(A a, B b) {
        // overwrite the existing variables
        this.a = a;
        this.b = b;
    }
}

class B {
}

class C {
}

Note that i force the new constructor visibility to be package private not to pollute the SUT's api and also choose to instantiate the DOCs inside the SUT for client usage convenience.

SUT: System under test (A)

DOC: depended-on component (B and C)

What do you think ? Thanks in advance.



Related Questions


Integration tests, but how much?

Updated February 28, 2017 08:05 AM

How to manage non-unit tests in a project?

Updated April 26, 2017 14:05 PM


Testing strategy for wrapper class

Updated June 01, 2015 22:02 PM